【发布时间】:2019-10-15 11:48:57
【问题描述】:
我在 Vue 中创建了一个自定义复选框组件,它可以很好地处理存储在根实例中的数据。我计划在各种情况下重用这个组件(以及我正在构建的许多其他组件)。我不想每次使用组件时都必须更新或编辑根 Vue 实例,并且只想将数据存储在组件本身中。已选中/未选中的布尔值需要是响应式的。
我尝试过使用计算值,但也无法让它工作。如果需要,我愿意使用它。
(此版本无效)
<body>
<script src="https://unpkg.com/vue@2.6.10"></script>
<div id="app">
<checkbox-item v-model="checkData">Active</checkbox-item>
{{ checkData }}
</div>
</body>
</html>
<script>
Vue.component('checkbox-item', {
template: `
<label class="checkbox-item">
<input type="checkbox" :checked="value"
@change="$emit('input', $event.target.checked)"
class="checkbox-input">
<span class="checkbox-label">
<slot></slot>
</span>
</label>
`,
data: function() {
return {
checkData: null
}
},
props: ['value']
})
new Vue({
el: '#app',
})
</script>
(此版本有效,但我再次需要数据不在根实例中)
<body>
<script src="https://unpkg.com/vue@2.6.10"></script>
<div id="app">
<checkbox-item v-model="checkData">Active</checkbox-item>
{{ checkData }}
</div>
</body>
<script>
Vue.component('checkbox-item', {
template: `
<label class="checkbox-item">
<input type="checkbox" :checked="value"
@change="$emit('input', $event.target.checked)"
class="checkbox-input">
<span class="checkbox-label">
<slot></slot>
</span>
</label>
`,
props: ['value']
})
new Vue({
el: '#app',
data: {
checkData: null
}
})
</script>
我得到的错误是:
[Vue 警告]:属性或方法“checkData”未在实例上定义,但在渲染期间被引用。通过初始化该属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件。请参阅:https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。
并且checkData 不像在工作示例中那样具有反应性。
编辑:好的,这就是有效的!我肯定会考虑使用 SFC 和其他代码组织方法,但现在它仍然在一个 html 文件中。有没有人认为这从长远来看是行不通的?
<body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<checkbox-item></checkbox-item>
</div>
</body>
</html>
<script>
Vue.component('checkbox-item', {
template: `
<label class="checkbox-item">
<input type="checkbox" v-model="checkData"
class="checkbox-input">
<span class="checkbox-label">
<slot>Active: {{checkData}}</slot>
</span>
</label>
`,
data: function(){
return {
checkData: this.checked
}
},
})
new Vue({
el: '#app',
})
</script>
【问题讨论】:
-
我强烈建议看看 VueMastery 的介绍和高级组件课程。了解 v-on="$listeners" 和 v-bind="$attrs" 会对你有很大帮助。他们还深入探讨了使用槽和作用域槽的组合。最后,VueLand Discord 是获得帮助的绝佳免费资源。
标签: vue.js vuejs2 vue-component