我有一个 vue 组件,如下所示,在子模板中我有一个文本输入,我想使用 v-model 将其链接到父级中的 var。但它不起作用。 我怎样才能实现这一目标?
我目前正在使用 Vue.js 1.23(由于某些原因需要使用它,因此无法升级)
谢谢
// this is in my Vue app
textWidget: ''
// this is called directly in the page.html
<text-widget v-show="getCurrentWidgetType() == 'text-widget'" :textWidget="textWidget"></text-widget>
// declaring the component just before my main vue app
Vue.component('text-widget', {
template: `{% include('templates/widgets/text.html.twig') %}`,
date: function () {
return {
textWidget:textWidget
}
}
})
更新:
// declared just before my Vue app
Vue.component('text-widget', {
template: `{% include('templates/widgets/text.html.twig') %}`,
props: ['textwidgetmodel']
})
// text input in the component child
<input type="text" v-model="textwidgetmodel">
// html in the main html page
// this input was just for testing. This confirmed that the props binding did indeed work,
// the only problem is it seems to be a one way binding from parent to child.
// I assume this because when I change the value with the text input below then it changes the value even in the component element.
// But when a value in inputted into the child text input nothing happens to the value in the partent
<input type="text" v-model="textWidget" />
<text-widget v-show="getCurrentWidgetType() == 'text-widget'" :textwidgetmodel=textWidget></text-widget>
最佳答案
好吧,所以我猜输入元素的某个地方将模型绑定(bind)到 textWidget
,如下所示:
<input type="text" v-model="textWidget"/>
你想通过 props 将其发送到你的子组件,所以你这样做了
<text-widget v-show="getCurrentWidgetType() == 'text-widget'" :textWidget="textWidget"></text-widget>
这几乎很好,但还不够,因为模板中的 Prop 应该以短横线格式格式化,所以这是正确的设置
<text-widget v-show="getCurrentWidgetType() == 'text-widget'" :text-widget="textWidget"></text-widget>
然后您应该将该 prop 定义到组件逻辑中,以便 Vue 知道要使用什么(现在不需要数据模型,除非您有其他一些基于组件的数据):
// declaring the component just before my main vue app
Vue.component('text-widget', {
template: `{% include('templates/widgets/text.html.twig') %}`,
props: ['textWidget']
})
关于javascript - 将子级中的 v-model 链接到父级值 vue js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111636/