What are the methods for creating components in Vue? Below I will share with you a summary of two methods of creating components in Vue. It has a good reference value and I hope it will be helpful to everyone.
Summary of two methods of creating components
1. Global registration
2. Local registration
var child=Vue.extend({}) var parent=Vue.extend({})
Vue.extend() global method generates a constructor and creates a subclass
Use the basic Vue constructor to create a "subclass".
Writing like this is very cumbersome. So vue was simplified
Use Vue.component() to directly create and register components:
Vue.component(id,options) global method is used to register global components
id is a string type, which is the name of the registered component
options is an object
// 全局注册,my-component1是标签名称 Vue.component('my-component1',{ template: '<p>This is the first component!</p>' }) var vm1 = new Vue({ el: '#app1' })
Vue.component() The first parameter is the label name, and the second parameter is an options object. Use the template attribute of the option object to define the component template.
Using this method, Vue will automatically call Vue.extend() behind the scenes.
Implement local registration in the components attribute of the option object:
var vm2 = new Vue({ el: '#app2', components: { // 局部注册,my-component2是标签名称 'my-component2': { template: '<p>This is the second component!</p>' }, // 局部注册,my-component3是标签名称 'my-component3': { template: '<p>This is the third component!</p>' } } })
==Local registration is placed in the option Created in the object==
Note: Here are components, multiple components can be defined in it.
The simplified writing method is like this
<body> <p id='box'> <parent> </parent> </p> <script src='js/vue.js'></script> <script> Vue.component('parent',{ template:`<p><h1>我是父组件</h1><child></child></p>`, components:{ 'child':{ template:`<h1>我是子组件</h1>` } } }) new Vue({ el:'#box' }) </script> </body>
Register a parent Parent component. Then register a child subcomponent in the options object of the parent component. Write the tag of the child component into the template of the parent component.
The style structure on the page is
<p> <h1>我是父组件</h1> <h1>我是子组件</h1> </p>
Note: Subcomponents registered locally cannot be used alone Use directly!
If the tag is hung in p, an error will be reported
<p id='box'> <child></child> </p>
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to define your own select component based on ng-alain in angular?
How to implement watch monitoring objects and corresponding value changes in vue
How to solve the problem that Vue cannot detect arrays or Problems with object changes?
The above is the detailed content of How to create components in Vue. For more information, please follow other related articles on the PHP Chinese website!