首页 技术 正文
技术 2022年11月23日
0 收藏 600 点赞 4,315 浏览 1002 个字

处理边界情况之使用$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 来管理应用的状态。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,906
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,430
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,247
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,058
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,690
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,727