我需要访问每个组件中的hostname
变量.
把它放在data
里是个好主意吗?
如果我这么做了,我能用this.hostname
美元到处叫唤它,这是对的吗?
我需要访问每个组件中的hostname
变量.
把它放在data
里是个好主意吗?
如果我这么做了,我能用this.hostname
美元到处叫唤它,这是对的吗?
Warning:下面的答案是使用Vue 1.x、 Vue 2中删除了twoWay
个数据Mutations .x(幸运的!).
对于附加到全局对象(web浏览器中的窗口对象)的"全局"变量,声明变量的最可靠方法是显式地在全局对象上设置它:
window.hostname = 'foo';
然而,从Vue的层次 struct 透视图(根视图模型和嵌套组件)来看,数据可以向下传递(如果指定了双向绑定,则可以向上变异).
例如,如果根viewModel有hostname
个数据,则该值可以绑定到嵌套组件,其中v-bind
指令为v-bind:hostname="hostname"
或简称:hostname="hostname"
.
在组件内,可以通过组件的props
属性访问绑定值.
最终,数据将被代理到this.hostname
,如果需要,可以在当前Vue实例中使用.
var theGrandChild = Vue.extend({
template: '<h3>The nested component has also a "{{foo}}" and a "{{bar}}"</h3>',
props: ['foo', 'bar']
});
var theChild = Vue.extend({
template: '<h2>My awesome component has a "{{foo}}"</h2> \
<the-grandchild :foo="foo" :bar="bar"></the-grandchild>',
props: ['foo'],
data: function() {
return {
bar: 'bar'
};
},
components: {
'the-grandchild': theGrandChild
}
});
// the root view model
new Vue({
el: 'body',
data: {
foo: 'foo'
},
components: {
'the-child': theChild
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<h1>The root view model has a "{{foo}}"</h1>
<the-child :foo="foo"></the-child>
如果我们需要向上修改父数据,我们可以在绑定声明中添加一个.sync
修饰符,比如:foo.sync="foo"
,并指定给定的"props"应该是twoWay
绑定的数据.
因此,通过改变组件中的数据,父组件的数据将分别发生改变.
例如:
var theGrandChild = Vue.extend({
template: '<h3>The nested component has also a "{{foo}}" and a "{{bar}}"</h3> \
<input v-model="foo" type="text">',
props: {
'foo': {
twoWay: true
},
'bar': {}
}
});
var theChild = Vue.extend({
template: '<h2>My awesome component has a "{{foo}}"</h2> \
<the-grandchild :foo.sync="foo" :bar="bar"></the-grandchild>',
props: {
'foo': {
twoWay: true
}
},
data: function() {
return { bar: 'bar' };
},
components: {
'the-grandchild': theGrandChild
}
});
// the root view model
new Vue({
el: 'body',
data: {
foo: 'foo'
},
components: {
'the-child': theChild
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<h1>The root view model has a "{{foo}}"</h1>
<the-child :foo.sync="foo"></the-child>