处理边界情况之使用$root访问根实例

点击打开视频教程

在每个 new Vue 实例的子组件中,其根实例可以通过 $root property 进行访问。

例如,在这个根实例中:

src\main.js

import Vue from 'vue'
import App from './App.vue'
//引入ElementUI组件库
import ElementUI from 'element-ui';
//引入ElementUI全部样式
import 'element-ui/lib/theme-chalk/index.css';
// import {Plugin1,Plugin2} from './plugins/plugins.js'
Vue.config.productionTip = false
//使用ElementUI
Vue.use(ElementUI)
// Vue.use(Plugin1,'参数1')
// Vue.use(Plugin2,'参数2')
new Vue({
  data: {
    foo: 1
  },
  computed: {
    bar: function () {
      return '满天星辰不及你'
    }
  },
  methods: {
    baz: function () { 
      return '满天星辰不及你吖'
    }
  },
  render: h => h(App),
}).$mount('#app')

所有的子组件都可以将这个实例作为一个全局 store 来访问或使用。

<template>
  <div id="app">
    <!-- 获取根组件的数据 -->
    {{ $root.foo }}
    <!-- 访问根组件的计算属性 -->
    {{ $root.bar }}
    <button @click="change">改变</button>
  </div>
</template>
<script>
export default {
  name: 'App',
  data(){
    return {
    } 
  },
  mounted(){
  },
  computed:{
  },
  methods:{
    // 写入根组件的数据
    change(){
      this.$root.foo = '末晨曦吖'
      // 调用根组件的方法
      let name = this.$root.baz()
      console.log(name);
    }
  }
}
</script>
<style scoped>
</style>

注意:对于 demo 或非常小型的有少量组件的应用来说这是很方便的。不过这个模式扩展到中大型应用来说就不然了。因此在绝大多数情况下,我们强烈推荐使用 Vuex 来管理应用的状态。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。