Vuejs single-file component. Vue file

Source: Internet
Author: User
Tags emit script tag

Vuejs customizes a . vue file, which can be used to write HTML, CSS, JS into a file, thus enabling the encapsulation of a component, a . vue file is a separate component. Because the. vue file is custom, the browser does not know it, so the file needs to be parsed. In the webpack build, you need to install Vue-loader to parse the. vue file. In the sumlime editor, we write the . Vue file and can install the Vue syntax highlight plugin to add support for the file.

Create a new Vue project with VUE-CLI and see what the. vue file looks like? in the process of creating a new project, you will be asked a few questions on the command line, select No when asked if you want to install Vue-router. After the completion of the project, we saw in the SRC directory there is a componet directory, there is a Hello.vue file, the contents are as follows, there are some limitations on the contents of the template

<template>  <div class= "Hello" >    default  {  ' hello '  ,  data () {    return  {      ' Welcome to Your vue.js App '}}  } </script><style scoped>H1, h2 {  font-weight:normal;} UL {  list-style-type:none;   0;} Li {  display:inline-block;   0 10px;} A {  color: #42b983;} </style>

As you can see, in the . Vue file, the template is HTML code, it defines what is displayed on the page, because there are variables, it can also be said to define a template, script is all JS code, It defines the data and its operations required in this component, the styleis a CSS style, defines the styling of the component, andscoped indicates that the CSS style written here applies only to that component and can qualify the scope of the style.

  An understanding of the object behind the export defalut in the script tag.

When you do not use the . Vue single file, we create a Vue root instance from the Vue constructor to start the Vuejs project, andthe Vue constructor accepts an object that has some configuration properties el, Data, component, template, etc., to support the application as a whole.

New Vue ({  ' #app ',  data: {        "Hello Vue"       }  })

In the . Vue file,the object after export default is the equivalent of the accepted objects in the new Vue () constructor, which are all the data needed to define the component, and how to manipulate the data, A more comprehensive export default object, with methods, data, and computed, can be seen that this object is identical to the object accepted in the new Vue () constructor. But be aware that data is written in different ways. In. The Vue component, data must be a function that returns a return (an object) that returns an object that is used by the component to implement.

Empty the Hello.vue content that comes with your project, and we'll write a component to experience the same.

 <template> <div class= "Hello" > <input type= "Txet" placeholder= "Please enter text" v-model= "MSG" @keypress. ent Er= "Enter" > <p>{{upper}}</p> </div></template><script> export  default   return   {msg:  ' hello '  this  .msg); }}, computed: {upper () { return  thi    s  .msg.touppercase ();    }}}  </script><style scoped> input {width:200px;  height:20px;  } p {color:red; }  </style> 

There is an input box on the page, and when the input is entered, the contents of the input box will be displayed synchronously, except that it is capitalized, and when the input is completed, pressing ENTER will pop up what we entered. To get the user input, we use the v-model instruction, which binds the user input to the variable, and its response, our variable value changes with the user input, which means we always get the user's latest input. The following uppercase display, using the computed property, the pop-up window is bound to a KeyPress event, by description, you will find that it is simply a Vue instance, in fact, it is a Vue instance. Each Vue component is a Vue instance, which makes it easier to understand the objects behind the export default.

  Communication between parent and child components

Each of the. vue files is a component, and the components and components are combined into one application, which involves communication between the components and the components, most commonly the communication between father and son. In Vue, another component is introduced through import in one component, which is the parent component, and the component being introduced is a subcomponent.

In our VUE-CLI project, thesrc folder has a App.vue file, its script tag,import Hello from './components/hello ', then App.vue is the parent component, andthe Hello.vue under the Components folder is a subcomponent. The parent component passes data to the child component through props, and the child component passes the data to the parent component through a custom event.

< Span lang= "en-US" >app.vue template   mes-father= "message from Father";   parent component passes data in How to receive it

< Span lang= "en-US" > in hello.vue props, which is an array mesfather string mes-father, no one by one corresponds.   This is mainly because, in the html element case is insensitive. If we write mesfather   will be converted to mesfather, equivalent to the sub-component we passed a js file, we define  props: ["Mesfather"], we are not receiving data because js is case-sensitive and can only be written as props: ["Mesfather"].   but in js file, Like this two-word spelling of the data, we are accustomed to use the Hump name method, so vue did a conversion, if the attribute in the component is -Indicates that it will automatically turn into camel-like.   incoming data is mes-father, converted into mesfather, we js inside write mesfather, each corresponding, sub-components can be accepted to the component. Props property is the same level as data,template of the subcomponents.

  The template changes for App.vue are as follows:

<template>  <div id= "app" >        

Hello.vue components, here or the project's own Hello.vue empty, write yourself, into the following content

<template>  <div class= "Hello" >    <p>{{mesFather}}</p>  </div></ template><script>default  {  props:[' Mesfather '}</ Script>

At this point, you see the message from the Father Word in the page , and the parent element passes the data to the child element successfully.

A child component passes data to the parent component and needs to use a custom event. For example, in Hello.vue , we write an input, receive user input, and we want to pass the user input data to the parent component. At this point,input needs to bind a KeyPress event to get the user's input, but also to launch a custom event, such as Valueup, as long as the parent component listens to this custom event, it is possible to know that the child component is going to pass the data to him. When a child component launches a custom event, it can also carry parameters, and the parent component can also accept parameters, parameters, or data to be passed when listening to the event.

in the hello.vue template, add an input box, give it a v-model to get the user's input, add the KeyPress event, use it to transmit the event, and transfer the data. script Add data, define variables to get user input, add methods to handle KeyPress event handler for enter, the entire Hello.vue file is as follows

<template> <div class= "Hello" > <!--Adding an input input box to add KeyPress event--<input type= "text" v-model= "I Nputvalue "@keypress. enter=" Enter "> <p>{{mesFather}}</p> </div></template><script >Exportdefault{props:[' Mesfather '],  //add data, user input bound to inputvalue variable, to get user inputDatafunction () {    return{inputvalue:‘‘}}, Methods: {Enter () { This. $emit ("Valueup", This. Inputvalue)//The subassembly emits a custom event valueup and carries the value to be passed to the parent component,      //if you want to pass a lot of values to the parent component, these values are listed as parameters, such as this. $emit (' Valueup ', This.inputvalue, this.mesfather);    }  }}</script>

In App.vue, the Hello component in the template binds a custom event,@valueUp = "Receive", which listens for events emitted by a subassembly, and then writes a p element that shows the data passed by the subassembly. , the<p> sub-component passes over the data {{ childmes }}</p>

Accordingly, in Scrpit,data, define a variable childmes, and in methods, define an event handler function reciever. The entire App.vue is modified as follows:

<template> <div id= "app" >  <!--Add custom event Valueup---Import Hello from'./components/hello 'Exportdefault{name:' App ', components: {Hello},//Add DataDatafunction () {    return{childmes:‘‘    }  },  //Add methods, custom event Valueup event handler recievemethods: {recieve:function(MES) {//The recieve event needs to be set parameters, which are the data passed by the subassembly, so the number of parameters must be consistent with the child elements passed over.        This. Childmes =mes; }  }}</script>

When you enter content in input, and then press ENTER, you see the data passed by the child component, and the child component passes the data to the parent component successfully.

When you enter data in input box and press ENTER, it triggers the Keypress.enter event, which invokes the event handler, enter, in Enter, we emit an event valueup, and carry a parameter due to the

In fact, in the sub-component, props the best way to write is props authentication, we wrote props:[' Mesfather ' in the subassembly Hello.vue, just expressed, it accepts a parameter mesfather, if written props authentication, Not only can it express what parameters it needs, but it can also express the parameter type, and Vue warns if there are errors. Now change the props to props verification of the wording, Hello.vue in the JS props modified as follows:

props: {      ' mesfather ': {          type:string,          default: ' From Father ',          required: true       }  }

If the communication between components and components is very complex, not only parent-child components, but also sibling components, then you need to use state management,Vuex

Vuejs single-file component. Vue file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.