Home >Web Front-end >Vue.js >A brief analysis of several ways to create components in Vue
Creating vue components is to split the code amount of vue instances and find different functions through different components. Here are three ways to create components in Vue. Friends in need can refer to them. I hope it will be helpful to everyone.
Method 1: Use Vue.extend to create a global Vue component
Instance:
var com1 = Vue.extend({ template: '<h3>这是使用 Vue.extend 创建的组件</h3>' // 通过 template 属性,指定了组件要展示的HTML结构 })
Use Vue.component
('component name', created component object) When creating a vue component, use the first letter of the name to name it. When referencing the component, change the uppercase to lowercase letters, and use # before the two words. ##- Connection; parameter one: a tag to introduce the component, parameter two:
template is the
HTML content displayed by the component.
<div id="app"> <!-- 如果要使用组件,直接,把组件的名称,以 HTML 标签的形式,引入到页面中,即可 --> <mycom1></mycom1> </div> <script> Vue.component('mycom1', Vue.extend({ template: '<h3>这是使用 Vue.extend 创建的组件</h3>' })) // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, }); </script>The result obtained is:
Method 2: Use Vue.component directly
<body> <div id="app"> <!-- 使用标签形式,引入自己的组件 --> <mycom2></mycom2> </div> <script> Vue.component('mycom2', { template:`<div> <h3>这是直接使用 Vue.component 创建出来的组件</h3> <span>123</span> </div> ` }) // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, methods: {} }); </script> </body>Result:
Method 3: Use Vue.component outside the controlled #app, and use the template element
inside the controlled #App Outside, use the template element to define the HTML template structure of the component<body> <div id="app2"> <login></login> <mycom3></mycom3> <login></login> </div> <template id="tmpl"> <div> <h1>这是通过 template 元素,在外部定义的组件结构,这个方式,有代码的只能提示和高亮</h1> <h4>好用,不错!</h4> </div> </template> <template id="tmpl2"> <h1>这是私有的 login 组件</h1> </template> <script> Vue.component('mycom3', { template: '#tmpl', }) // 创建 Vue 实例,得到 ViewModel var vm2 = new Vue({ el: '#app2', data: {}, methods: {}, filters: {}, directives: {}, components: { // 定义实例内部私有组件的 login: { template: '#tmpl2' } }, }) </script> </body>Output result: Note: No matter how the component is created, the content pointed to by the component's template has one and only one root element.
vue.js Tutorial"
The above is the detailed content of A brief analysis of several ways to create components in Vue. For more information, please follow other related articles on the PHP Chinese website!