Vue.js 2.x之组件的定义和注册图文详解(4)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://www.jb51.net/Vue2.5.16.js"></script> </head> <body> <div> <!-- Vue提供了 component ,来展示对应名称的组件 --> <!-- 【重要】component 是一个占位符, `:is` 属性,可以用来指定要展示的组件名称。这里,我们让 login 组件显示出来 --> <component :is="'login'"></component> </div> <script> // 组件名称是 字符串 Vue.component('login', { template: '<h3>登录组件</h3>' }) Vue.component('register', { template: '<h3>注册组件</h3>' }) // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: { comName: 'login' // 当前 component 中的 :is 绑定的组件的名称 }, methods: {} }); </script> </body> </html>

上方代码中,提取关键代码如下:     

<component :is="'login'"></component>

如果我想让register组件显示出来,借助<component>标签可以这样做:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://www.jb51.net/Vue2.5.16.js"></script> </head> <body> <div> <!-- Vue提供了 component ,来展示对应名称的组件 --> <!-- 【重要】component 是一个占位符, `:is` 属性,可以用来指定要展示的组件名称 --> <component :is="'register'"></component> </div> <script> // 组件名称是 字符串 Vue.component('login', { template: '<h3>登录组件</h3>' }) Vue.component('register', { template: '<h3>注册组件</h3>' }) // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: { comName: 'login' // 当前 component 中的 :is 绑定的组件的名称 }, methods: {} }); </script> </body> </html>

上方代码中,提取关键代码如下:    

<component :is="'register'"></component>

因此,如果要实现组件之间的切换,我们可以给<component>标签里的is属性值设置为变量即可,来看看代码实现。

实现组件切换的完整代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://www.jb51.net/vue2.5.16.js"></script> </head> <body> <div> <!-- 点击按钮后,设置变量`comName`为不同的值,代表着后面的component里显示不同的组件 --> <a href="" @click.prevent=" comName='login'">登录</a> <a href="" @click.prevent=" comName='register'">注册</a> <!-- Vue提供了 component ,来展示对应名称的组件 --> <!-- component 是一个占位符, :is 属性,可以用来指定要展示的组件的名称 --> <!-- 此处的`comName`是变量,变量值为组件名称 --> <component :is="comName"></component> </div> <script> // 组件名称是 字符串 Vue.component('login', { template: '<h3>登录组件</h3>' }) Vue.component('register', { template: '<h3>注册组件</h3>' }) // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: { comName: 'login' // 当前 component 中的 :is 绑定的组件的名称 }, methods: {} }); </script> </body> </html>

效果:

总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/fc89264d959a7196955e5d8856606b05.html