Home > Article > Web Front-end > Introduction to two ways to implement component switching in Vue (with code)
The content of this article is an introduction to the two ways of implementing component switching in Vue (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Several ways to switch components of Vue
Method 1: V-if and v-else are used in combination to achieve switching
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script rel="script" src="js/vue-2.4.0.js"></script></head><body> <div id="app"> <a href="" @click.prevent="flag=true">登陆</a> <a href="" @click.prevent="flag=false">注册</a> <login v-if="flag"></login> <register v-else="flag"></register> </div><script> *<!--定义登录组件-->* Vue.component('login',{ template :'<h3>登陆组件</h3>' }); *<!--定义注册组件-->* Vue.component('register',{ template :'<h3>注册组件</h3>' }); *<!--创建Vue实例-->* var vm = new Vue({ el : '#app', data :{ flag : true, }, methods:{}, });</script></body></html>
Running results:Click to log in or register to enter the corresponding component module
##Note: Use v-if and v-else to achieve switching. You can only switch between two components and cannot switch between multiple components.
Method 2: Use the component element provided by Vue to implement component switching
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script rel="script" src="js/vue-2.4.0.js"></script></head><body> <div id="app2"> <!-- 链接修改comName的值--> <a href="" @click.prevent="comName = 'login' ">登陆2</a> <a href="" @click.prevent="comName = 'register' ">注册2</a> <!-- component 是一个占位符, :is 属性,可以用来指定要展示的组件的名称 --> <component :is=" comName "></component> </div><script> //组件名称是 字符串 Vue.component('login',{ template :'<h3>登陆组件</h3>' }) Vue.component('register',{ template :'<h3>注册组件</h3>' }) //实例 var vm2 = new Vue({ el : '#app2', data :{ comName : 'login',//当前 component 中的 :is 帮i的那个的组件的名称 }, methods:{}, });</script></body></html>This method can be used to define multiple component switching. It should be noted that the
component name must correspond to
How the node server implements the acquisition of Douban data (code)
vue implements the homepage tab imitating today's headlines Function
The above is the detailed content of Introduction to two ways to implement component switching in Vue (with code). For more information, please follow other related articles on the PHP Chinese website!