【问题标题】:I am trying to declare getTemp variable global so that i can use it in other function. VUE.JS我正在尝试将 getTemp 变量声明为全局变量,以便我可以在其他函数中使用它。 Vue.JS
【发布时间】:2017-05-14 00:39:54
【问题描述】:

我正在尝试将 getTemp 变量声明为全局变量,以便可以在其他函数中使用它。 VUE.JS

var weather = new Vue({
    el: '#weather',

    data: {
        getTemp: []
    },

    created: function () {
        this.fetchData();
    },        

    methods: {
        fetchData: function () {
            this.$http.get('https://vt')
                      .then(response => {
                         this.getTemp = response.data;

                      })
        }
    },
})
;

【问题讨论】:

  • 你是指其他组件吗?

标签: javascript vue.js


【解决方案1】:

根实例data 属性可通过this.$root.variableName 在整个应用程序中访问:

new Vue({
  el: '#app',
  data: {
    getTemp: 'Hello World!'
  },
  components: {
    'child1': {
      template: `<div><p>child1, getTemp: {{ $root.getTemp }}</p>
      	<subchild></subchild>
      </div>`,
      components: {
        'subchild': {
          template: `<span>Subchild test: {{ $root.getTemp }}</span>`
        }
      }
    },
    'child2': {
      template: `<p>child2, getTemp: {{ $root.getTemp }}</p>`
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <child1></child1>
  <child2></child2>
</div>

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    相关资源
    最近更新 更多