Vue中实现用动态组件代替路由的效果
Vue.js提供了一个特殊的元素用来动态地挂载不同的组件,使用 is 特性来选择要挂载的组件。
话不多说,直接上代码
可直接复制粘贴运行。一个简易的动态组件Demo,仅供参考
<!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="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<component :is="currentView"></component>
<button @click="handleChangeView('A')">切换到A</button>
<button @click="handleChangeView('B')">切换到B</button>
<button @click="handleChangeView('C')">切换到C</button>
</div>
<script>
var app = new Vue({
el: '#app',
components: {
comA: {
template: '<div>组件A</div>'
},
comB: {
template: '<div>组件B</div>'
},
comC: {
template: '<div>组件C</div>'
}
},
data:{
currentView:'comA'
},
methods:{
handleChangeView:function(component){
this.currentView = 'com' + component
}
}
})
</script>
</body>
</html>