gpt4 book ai didi

javascript - 无法访问 Template Vue 中的状态属性

转载 作者:行者123 更新时间:2023-12-03 01:06:59 24 4
gpt4 key购买 nike

我是 Vue 新手。我正在尝试从在线视频中学习 Vue。在下面的代码片段中,在 Counter 对象内,如果我更改模板以渲染函数,代码就会开始工作。

我不明白为什么?

-----HTML----

<div id="app">
<counter></counter>
<counter></counter>
<counter></counter>
<button @click="inc">increment</button>
</div>

------脚本标签------

const state = new Vue({
data: {
count: 0
},
methods: {
inc() {
this.count++;
}
}
});

const Counter = {
template: `<div>{{state.count}}</div>`
}

new Vue({
el: '#app',
components: {
Counter
},
methods: {
inc() {
state.inc();
}
}
})

如果我将 Counter 内的模板更改为此,它就可以工作

render: h => h('div', state.count)

最佳答案

state 是一个 Vue 实例,因此 data 属性中的变量可以作为 state 中的属性进行访问,即:state. count,或 state 实例内部的 this.count

由于 state.count 有效,因此您可以在 state 实例化下方的任何位置访问它。

然后 render: h => h('div', state.count) 变得有效。

现在,在 template 中访问的任何属性都必须是 Vue 实例或组件的内部属性,或者 Countthis 的属性。

因为Counter组件中的模板会被转换为这个对应的渲染函数:

render(h) {
return h('div', this.state.count)
}

{{state.count}} 不是指 state.count 变量,而是 Counter 组件的属性,this.state.count.

因此,为了举例(在实际项目中您不会执行任何操作),以下是如何使 state.countCounter 模板中有效:

const Counter = {
template: `<div>{{state.count}}</div>`,
data: () => ({
state: {
count: state.count
}
})
}

关于javascript - 无法访问 Template Vue 中的状态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353229/

24 4 0