注册和使用组件
在vue2中创建组件,并且使用它。
首先在main.js中创建vue实例:
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
render: h => h(App)
})
创建helloworld组件,即创建hellworld.vue文件: 用export default暴露,以被调用这个组件。
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
msg: "Welcome to Your Vue.js App",
};
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1 {
font-weight: normal;
}
a {
color: #42b983;
}
</style>
在app.vue中注册并引用组件hello:
<template>
<div id="app">
<img src="./assets/logo.png">
<hello></hello>
</div>
</template>
<script>
import hello from "./components/HelloWorld"
export default {
name: 'App',
components: {
hello,
},
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
新建命令窗口:npm run dev (有的是 npm run serve)
打开连接http://localhost:8080:
组件间的通信
创建一个Bus.js文件暴露实例。用以承载通信:
import Vue from 'vue';
const Bus = new Vue();
export default Bus;
在发出信息的组件中设置事件:
事件写在methods中。
Bus.$emit(“data-aside2”, this.year);第一个参数是事件名字,第二个是要传递的信息。
<template>
<div>
<el-menu>
<el-submenu
v-for="(item, index) in items"
:key="index"
:index="index + ''"
>
<template slot="title"
><i class="el-icon-user"></i>{{ item.grade }}</template
>
<el-menu-item
:index="index + '0.4'"
@click="setgrade(item.grade), send0(), send1()"
><i class="el-icon-s-custom"></i>社团负责人</el-menu-item
>
<el-menu-item
:index="index + '0.6'"
@click="setgrade(item.grade), send0(), send2()"
><i class="el-icon-s-custom"></i>社团成员</el-menu-item
>
</el-submenu>
</el-menu>
</div>
</template>
<script>
import Bus from "../../../assets/js/Bus";
export default {
name: "Asideedge",
data() {
return {
clickState: true,
};
},
methods: {
send0() {
Bus.$emit("data-aside0", this.clickState);
},
send1() {
Bus.$emit("data-aside1", this.year);
console.log(this.year);
},
send2() {
Bus.$emit("data-aside2", this.year);
console.log(this.year);
},
},
};
</script>
在接收信息的组件中设置监听事件。 Bus.$on(“data-aside2”, (msg) => { this.msg = msg; }); 第一个参数被监听的那个事件的名字,第二个用处理接收的信息。
<template>
<div class="home">
<Mainbody v-show="state"></Mainbody>
<Emptybody v-show="!state"></Emptybody>
</div>
</template>
<script>
import Bus from "../../assets/js/Bus";
import Mainbody from "./componnents/mainbody.vue";
import Emptybody from "./componnents/emptybody.vue";
export default {
name: "Home",
components: {
Mainbody,
Emptybody,
},
data() {
return {
msg:"成员信息",
state: false,
};
},
mounted() {
Bus.$on("data-aside0", (state) => {
this.state = state;
});
Bus.$on("data-aside1", (msg) => {
this.msg = msg;
});
Bus.$on("data-aside2", (msg) => {
this.msg = msg;
});
},
};
</script>
这样被监听的事件和监听它的事件都设置完毕就可以通信了。
|