javascript - 将子级中的 v-model 链接到父级值 vue js

标签 javascript data-binding vue.js

我有一个 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/

相关文章:

c# - WPF - 是否可以否定数据绑定(bind)表达式的结果?

vue.js - HereMaps Vue : trying to add behavior but H. mapevents 未定义

typescript - VS Code在Vue+TypeScript项目中找不到模块,WebStorm没问题

javascript - 从数组中删除指定值?

javascript - 如何在 Node.js 中使用代理

javascript - 如果单词出现 n 次,则将更改应用于元素

wpf - 使用 MVVM 的上下文菜单项命令绑定(bind) WPF

javascript - 使用 ng-html-bind 时无法滚动

c# - 如何提示一个新窗口显示所选项目的模型数据?

php - 在 Laravel 5 中,如何在启用 vue 的模板上转储变量?