Home  >  Article  >  Web Front-end  >  One hour to get started with vue components (recommended collection)

One hour to get started with vue components (recommended collection)

WBOY
WBOYforward
2021-12-27 19:07:031918browse

This article brings you knowledge about vue components, including how to instantiate multiple vue objects, global components and local components, as well as passing values ​​from parent to child, etc. I hope it will be helpful to everyone.

One hour to get started with vue components (recommended collection)

First introduction to component application

Instantiate multiple vue objects

Use new creates multiple vue objects and names them, and they can access each other through variables
Example: Object 2 modifies the name variable of object 1

<!-- 第一个根元素 -->
<div>这里是:{{name}}</div> 

<!-- 第二个根元素 -->
<div>
    <p>这里是:{{name}}</p>
<br>
    <button>change-one-name</button>
    <!-- 点击后修改vue-app-one的name值-->
</div>
 // 第一个vue对象var one = new Vue({
    el:"#vue-app-one",
    data:{
        "name":"ccy1"
    }})

 // 第二个vue对象var two = new Vue({
    el:"#vue-app-two",
    data:{
        "name":"ccy2"
    },
    methods:{
        // 修改vue-app-one的name为'ccy333'
        changeName:function(){
            one.name = 'ccy333'
        }
    }})

Effect: After clicking, modify "ccy1" to "ccy333"

One hour to get started with vue components (recommended collection)

Global components

Definition and use

  • Define global components, You need to give the component a name. When calling, use the component name as the label name; it is equivalent to a custom label. This label can contain many sub-html tags;
  • These sub-html tags are defined in the template attribute of the component , every time the component is called, the tag in the template is rendered
  • in the template must have only one root element
  • In the component, data is a function, return the data back
  • You can still use this to call the data defined in data

Example:

Define component:

① Define a component, named my-component
② It contains data: name and method: changeName
③ The rendered html effect has a p tag, including A button, when the button is clicked, the name is modified
④ Naming convention: camelCase (camel case naming method) and kebab-case (dash separated naming)

  • When written as a label, encounter The naming of uppercase letters needs to be changed to lowercase and a cross bar is used to connect the two parts before and after. For example, when defining a component, name it myComponent, and when writing it as a label, it should be written as my-component> ;
  • You can also use the horizontal bar method to name components when defining them;
  • If you use myComponent when defining and use my-component> for the label, it is OK, the system Automatically identify
// 自定义的全局组件my-component// template中只有一个根元素p标签,里面包含一个button按钮Vue.component('my-component',{
    template:`<p>
        我的名字是:{{name}}
        <button>btn</button>
        </p>`,
    data(){
        return {
            name:'ccy'
        }
    },
    methods:{
        changeName:function(){
            this.name = '安之'
        }
    }})// vue对象1new Vue({
    el:"#vue-app-one",})// vue对象2new Vue({
    el:"#vue-app-two",})

Use components:

① Use ## under the root element corresponding to the vue object (el specifies the tag) # ② Since it is a global component, it can be used under any vue object
③ Components are reusable and can be used multiple times under a vue object, and the components are independent of each other

<p>
    <my-component></my-component>
    <my-component></my-component></p> <p>
    <my-component></my-component></p>

Effect:
One hour to get started with vue components (recommended collection)

data is a function

In the vue object, the data attribute value is an object, For example:

One hour to get started with vue components (recommended collection) But in the global component, the same data may be used by multiple vue objects. When each object does not maintain a separate copy of data, if a certain vue object is modified If a variable in data is deleted, other vue objects will be affected when they obtain data;

If we use the above example as a case, if the data in the component is an object (reference), other places will not change, both Vue objects share the same name variable; when I change the name data through one of the Vue objects (that is, click any btn button), the name obtained by the other object also changes (the 'ccy' at other buttons also changes Was changed to 'Anzhi')

Therefore, in order to ensure the independence of data, that is,

each instance can maintain an independent copy of the returned object, data is Each instance returns a copy of newly created data, and the data obtained by different vue objects does not affect each other

In vscode, the data in the component is not allowed to be an object, and an error will be reported:

 [Vue warn]:

The “data” option should be a function that returns a per-instance value in component definitions.

Local components

    Local components are registered in a vue object.
  • Only the vue object that has registered the local component can use this local component
Example:


Local component definition:

// template仅一个根元素:ulvar msgComponent = {
	 // 数据是自身提供的 (hobbies)
    template:`
  • {{hobby}}
`,     data(){         return {             hobbies:['看剧','看动漫','吃好吃的']         }     }}

Register local component:

// 仅由注册过该局部组件的vue对象才能使用,此处为p#vue-app-one// 注意命名规范,components中对象的key将会被作为标签名,多个单词拼接的命名需使用横杆法// 可以写成msg-component,此处直接简化了命名为msg,new Vue({
    el:"#vue-app-one",
    components:{
        "msg": msgComponent    }})

Use in the html file:

<p>
    </p><p>这里是vue-app-one</p>
    <mycomponent></mycomponent>
    <mycomponent></mycomponent>
    <p>我的爱好:</p>
    <msg></msg> <!--使用局部组件-->

Effect: The part circled in the red box is rendered by the local component
One hour to get started with vue components (recommended collection)

Passing value/reference from parent to child: prop

Static value passing

Create subcomponent:

var titleComponent = {
    props:["title"],
    template:`<p>{{title}}</p>`
    // 所需要的数据title由父组件提供}

在父组件的components属性中注册子组件:

new Vue({
    el:"#vue-app-one",
    components:{
        "msg": msgComponent,
        "titleComponent":titleComponent    },})

在父组件上使用子组件:

<!-- p#vue-app-one为父组件 --><p>
    </p><p>这里是vue-app-one</p>
    <mycomponent></mycomponent>
    <mycomponent></mycomponent>
	<!--使用子组件title-component,并传值"我的爱好:"给子组件-->
    <title-component></title-component>
    <msg></msg>

效果:红框标记处就是父向子传值并展示

One hour to get started with vue components (recommended collection)

动态传值:v-bind

定义子组件:

var titleComponent = {
    props:["title"],
    template:`<p>{{title}}</p>`}

在父组件的components属性中注册子组件:

new Vue({
    el:"#vue-app-one",
    components:{
        "msg": msgComponent,
        "titleComponent":titleComponent    },
    data(){
        return {
            title:"my hobbies are ",
        }
    }})

使用子组件,通过绑定父组件data中的变量title来实现动态传值:

<!-- p#vue-app-one为父组件 --><p>
    </p><p>这里是vue-app-one</p>
    <mycomponent></mycomponent>
    <mycomponent></mycomponent>
    <!-- 动态绑定title -->
    <title-component></title-component>
    <msg></msg>

效果:红框处就是动态绑定获取数据的展示
One hour to get started with vue components (recommended collection)
传递数组等复杂数据时,也可以使用v-bind来动态传值,如:
需要向子级传递hobbies数组,在vue实例对象(父)中创建数据hobbies

new Vue({
    el:"#vue-app-one",
    components:{
        "msg": msgComponent,
        "titleComponent":titleComponent    },
    data:{
        title:"my hobbies are ",
        hobbies:['看剧','看动漫','吃好吃的'], //需要向子组件传递的数据
    }})

定义子组件

var msgComponent = {
    template:`
            <p>{{hobby}}</p>            `,
    props:["hobby"],
    data(){
        return {   
        }
    }}

使用子组件

<!-- p#vue-app-one为父组件 --><p>
    </p><p>这里是vue-app-one</p>
    <mycomponent></mycomponent>
    <mycomponent></mycomponent>
    <title-component></title-component>
    <!-- 动态传值:hobbies -->
    <msg></msg>

效果:
One hour to get started with vue components (recommended collection)
跳回“一点想法”处

子向父:事件传值$emit

        子组件不能通过prop向父组件传递数据,需要使用事件向父组件抛出一个值,告知父组件我需要实现一个功能,由父组件处理这个事件

例子:点击按钮,改变名称chinesename
(由于data变量名不支持chinese-name形式,花括号里不支持chineseName形式,所以这里我都用了小写,此处记录一下,日后学到了新知再来填坑)

先在父组件的data中定义chinesename的初始值:

new Vue({
    el:"#vue-app-one",
    data:{
         chinesename:"anzhi" // chinesename初始值
    }})

创建子组件,并注册事件change-name(就像click事件一样,需要让系统能够辨认这是一个事件并监听,当事件被触发时,执行某项约定好的操作):

  Vue.component('blog-post', {
    props: ['chinesename'],
    template: `
      <p>
        </p><h3>{{ chinesename }}</h3>
        <button>
            修改名字
        </button>
          `
    // blog-post组件包含一个h3,显示chinesename,和一个按钮
    // 点击这个按钮,触发change-name事件,将"ruosu"作为参数传递给指定的处理函数onChangeName
  })

在父组件中使用子组件,定义change-name的处理函数为onChangeName:

<p>
    </p><p>这里是vue-app-one</p>
	<!-- v-bind:通过prop给子组件传递chinesename的初始值 -->
	<!-- v-on:子组件通过$emit给父组件传递新的chinesename的值 -->
	<p>
	      <blog-post></blog-post>
	 </p>

在父组件处定义事件处理函数onChangeName:

new Vue({
    el:"#vue-app-one",
    data:{
          chinesename:"anzhi"
    },
    methods:{
        onChangeName:function(value){
        	// 将chinesename换成传递过来的数据
            this.chinesename=value        }
    }})

效果:
One hour to get started with vue components (recommended collection)

一点想法

关于父子组件的区分,在此写一点总结,还是日后学了新知识再来填坑 ┗|`O′|┛ 嗷~~

      官网中没有很明确指明两者的定义和区别,在网上搜了一圈,觉得比较多人认可并且好理解的是:

  • el指定的根元素为父组件(使用之处为父组件)
  • vue实例对象也可看做组件

      在前面这些父子传值的例子中,我们可以看到,对于局部组件,我们会在某个html根元素中注册并使用,所以此时el指定的根元素在html文件中是这个局部组件的父组件,局部组件在html使用时便是这个父组件的一份子,承担数据传输的责任
跳转到父向子动态传值案例

One hour to get started with vue components (recommended collection)
One hour to get started with vue components (recommended collection)

      再用绕口令说一波,即:title-component组件定义处与使用处,两者身份是不一样的,在定义处,它是局部组件,也是子组件,需注册才能使用;在使用处,它是根元素的包含一部分,根元素为父组件,而“它”,承担着父组件与子组件数据沟通的重任

这个总结在全局组件情况下也适用,使用该全局组件的根元素是父组件,如上面的子向父传值的案例,p#vue-app-one是父组件,作为父子组件沟通的桥梁,全局组件blog-post为子组件
跳转到子向父案例

图示:
One hour to get started with vue components (recommended collection)


如果是子组件又嵌套了子组件,被嵌套的组件是子子组件,以此类推

Use scaffolding to create projects and use components and pass values

You can read my article for CLI scaffolding installation steps. Using CLI scaffolding to create a project is simple and fast. In particular, page content and data transfer need to be written in .vue files, and each vue file is a module.
We complete a specific function by reasonably assembling each module (component). The cooperation between components and the role of parent-child value transfer are more obvious here. Each vue file can be regarded as a component. We can divide the page into several parts according to needs, such as navigation bar, middle content and bottom part. The implementation of each part is dispersed into various sub-components, including page display and data acquisition.

For example, a customized blog page:

  • The main page is composed of the vue-app main component, including the navigation bar, the middle part, and the bottom bar

  • The navigation bar is completed by the vue-header sub-component

  • The middle content is divided according to functions

    • Add blog: addBlob sub-component Component
    • Display blog: showBlob subcomponent
    • Modify blog: modifyBlob subcomponent
    • Click to display single blog content: singleBlob subcomponent
  • The bottom information bar is completed by vue-footer
    In addition to the main page, other sub-parts and components are divided according to functions to assist the main page display

## The schematic diagram of personal blog passing value from parent to child is as follows:

    Each sub-function is composed of different components, which are combined into a larger functional component
  • Click to display a single blog and modify the blog Both components need to obtain the blog ID from the main page in order to display and operate accordingly. This is a typical parent-to-child value transfer

  • One hour to get started with vue components (recommended collection)
[Related recommendations : "

vue.js tutorial"】

The above is the detailed content of One hour to get started with vue components (recommended collection). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete