总线/发布订阅模式/非父子组件间传值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./vue.js"></script>
<style>
</style>
</head>
<body>
<div id="app">
<child :content="hy"></child>
<child :content="mm"></child>
</div>
<script>
Vue.prototype.bus = new Vue();
Vue.component('child', {
props: ['content'],
data: function () {
return {
self_content: this.content
}
},
template: '<div @click="handleClick">{{self_content}}</div>',
methods: {
handleClick: function () {
this.bus.$emit('change', this.self_content)
}
},
mounted: function () {
var that = this;
this.bus.$on('change', function (content) {
that.self_content = content;
})
}
})
var vm = new Vue({
el: '#app',
data: {
hy: 'hy',
mm: 'mm'
}
})
</script>
</body>
</html>
作用域插槽,具名插槽,子组件的内容由父组件传递时适用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./vue.js"></script>
<style>
</style>
</head>
<body>
<div id="app">
<child>
<h1 slot="header">header</h1>
<template slot-scope="props">
<div>{{props.item}}</div>
</template>
<h1 slot="content">content</h1>
<h1 slot="bottom">bottom</h1>
</child>
</div>
<script>
Vue.prototype.bus = new Vue();
Vue.component('child', {
props: ['content'],
data: function () {
return {
self_content: this.content,
list: [1, 2, 3]
}
},
template: `<div @click="handleClick">
<slot name="header"></slot>
<slot name="content" v-for="item of list" :item="item"></slot>
<slot name="bottom"></slot>
</div>`,
methods: {
handleClick: function () {
this.bus.$emit('change', this.self_content)
}
},
mounted: function () {
var that = this;
this.bus.$on('change', function (content) {
that.self_content = content;
})
}
})
var vm = new Vue({
el: '#app',
data: {
hy: 'hy',
mm: 'mm'
}
})
</script>
</body>
</html>
动态组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./vue.js"></script>
<style>
</style>
</head>
<body>
<div id="app">
<component :is="currentComponent"></component>
</div>
<script>
Vue.prototype.bus = new Vue();
Vue.component('child', {
props: ['content'],
data: function () {
return {
self_content: this.content,
list: [1, 2, 3],
}
},
template: `<div v-once > sss </div>`,
})
var vm = new Vue({
el: '#app',
data: {
currentComponent: 'child'
}
})
</script>
</body>
</html>
v-once 当组件第一次被渲染的时候,这个指令会给组件放入内存中,切换的时候不会重新创建,直接从内存中拿出来,有效的提高静态内容的展示效率