我需要访问每个组件中的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>

Vue.js相关问答推荐

使用V-TOOLTIP(实例化)使工具提示在V-文本字段中显示清晰的图标

Vue 3组合式API如何测试是否发出正确的事件

我在 nuxt2 中看不到索引页

TailwindCSS 为什么前者比后者重要?

在keyup Vuejs 2上获取输入值

如何在Typescript语言Vuejs中使用watch功能?

如何将对象作为props传递并让组件更新子对象

在按键 vuejs 中只允许数字和一个小数点后 2 位限制

如何根据生产或开发模式读取不同的 .env 文件?

如何使用 vue-resource 添加额外的标头来发布请求?

在 vuejs 中将旧代码修改为 vue router 4

vue-test-utils:无法覆盖属性 $route,这通常是由于插件将该属性添加为只读值

VueJS 通过渲染传递数据

Vue 3 组合 API,如何在 setup() 函数中获取上下文父属性?

v-for 如何在继续之前判断未定义的列表

'不提供名为'createRouter'的导出'' vue 3、vite 和 vue-router

在路由更改之前显示确认对话框

使用 Spring Boot(VueJS 和 Axios 前端)禁止发布 403 帖子

Vue - 重用方法的最佳方式

在 Vue 中使用事件修饰符 .prevent 提交表单而不进行重定向