nu *_*est 4 javascript vue.js vuejs2
背景:我正在从1.0迁移到2.0.
目前,我正在使用嵌套组件.父母和孩子之间的关系非常好.但是,父组件和主Vue()实例之间的关系被破坏.在cssstyleVue()实例中的计算属性不会像我期望的那样基于$ emit()/ $ on()进行更新.
相关部分:
在HTML中使用父组件:
<f9-padding v-if="editable" ></f9-padding>
在父组件内
computed: {
cssstyle: function() {
var padding_style = this.padding();
bus.$emit('padding_changed', padding_style);
return padding_style;
}
}
Run Code Online (Sandbox Code Playgroud)
在主Vue()实例内部
computed: {
cssstyle: function() {
console.log('cssstyle computed');
bus.$on('padding_changed', function (padding_style) {
return padding_style;
});
return 'padding: 0px;';
},
...
Run Code Online (Sandbox Code Playgroud)
父内部的计算属性更新就好了.但是,主Vue()实例内的计算属性仅在页面加载时运行.我不明白如何从不使用<input>元素的父级发出数据.我在网站上发现的大多数例子都只关注<input>案例.我只是计算了属性数据的变化.我尝试使用此处显示的方法:http://rc.vuejs.org/guide/components.html#Custom-Events,但是我对此文档的关注是它讨论的是组件之间的事件监听而不是父级组件和主Vue()实例.
更新:我能够通过将父项的计算属性更改为此来解决此问题:
computed: {
cssstyle: function() {
var padding_style = this.padding();
this.$root.cssstyle = padding_style;
return padding_style;
}
}
Run Code Online (Sandbox Code Playgroud)
并将cssstyle从计算机移动到根Vue()实例中的数据.
data: {
cssstyle: 'padding: 0px;',
},
Run Code Online (Sandbox Code Playgroud)
但是,我觉得使用时有点脏:
this.$root.cssstyle
没有其他办法吗?
对于事件发出和收听,请在2.0文档中进行检查.
如果你this从你的发射custom-component:
cssstyle: function () {
/*...*/
this.$emit('onsomething', params)
}
Run Code Online (Sandbox Code Playgroud)
然后,无论你在哪里创建这个组件的实例,你都会做这样的事情
<tamplate>
<custom-component @onsomething="action"></custom-component>
</tamplate>
Run Code Online (Sandbox Code Playgroud)
然后在你的JS中:
methods: {
action: function (params) {
console.log('On something')
}
}
Run Code Online (Sandbox Code Playgroud)