Laravel + Vue 3:将项目添加到可组合数组的每个元素
Laravel + Vue 3: Add item to each element of array from Composable
我正在尝试将 toShow
添加到 hello
数组的每个元素,但循环不起作用。
来自 api/test
的响应(调用 TestController
)分配给 hello
。
Test.vue
<script>
import useTest from "../composables/test.js"
import { onMounted } from 'vue'
export default {
setup() {
const { hello, getHello } = useTest()
onMounted(getHello)
// trying to print the first element of hello to the console, output: undefined
console.log(hello[0])
// it's supposed to be an array but looping is not working
hello.forEach(element => {
console.log(element)
// trying to add new item here
element.toShow = false
});
return {
hello,
}
},
}
</script>
测试控制器:
public function index()
{
$hello = array(['id' => 13, 'name' => 'world'], ['id' => 14, 'name' => 'world!']);
return $hello;
}
可组合:test.js
import { ref } from 'vue'
import axios from 'axios'
export default function useTest() {
const hello = ref([]) // add ref to it coz otherwise I can't assign value coz it says it's read-only
// set value for hello from api
const getHello = async () => {
let response = await axios.get("/api/test")
hello.value = response.data.hello
}
return {
hello,
getHello,
}
}
你必须解包里面的 ref <script>
:
hello.value.forEach(element => { // whatever
您还应该 await
onMounted 挂钩中的 getHello() 并在那里迭代,而不是在 onMounted 之外。
我正在尝试将 toShow
添加到 hello
数组的每个元素,但循环不起作用。
来自 api/test
的响应(调用 TestController
)分配给 hello
。
Test.vue
<script>
import useTest from "../composables/test.js"
import { onMounted } from 'vue'
export default {
setup() {
const { hello, getHello } = useTest()
onMounted(getHello)
// trying to print the first element of hello to the console, output: undefined
console.log(hello[0])
// it's supposed to be an array but looping is not working
hello.forEach(element => {
console.log(element)
// trying to add new item here
element.toShow = false
});
return {
hello,
}
},
}
</script>
测试控制器:
public function index()
{
$hello = array(['id' => 13, 'name' => 'world'], ['id' => 14, 'name' => 'world!']);
return $hello;
}
可组合:test.js
import { ref } from 'vue'
import axios from 'axios'
export default function useTest() {
const hello = ref([]) // add ref to it coz otherwise I can't assign value coz it says it's read-only
// set value for hello from api
const getHello = async () => {
let response = await axios.get("/api/test")
hello.value = response.data.hello
}
return {
hello,
getHello,
}
}
你必须解包里面的 ref <script>
:
hello.value.forEach(element => { // whatever
您还应该 await
onMounted 挂钩中的 getHello() 并在那里迭代,而不是在 onMounted 之外。