This is the 30th day of my participation in the August Challenge
el
The first way to write it
Our previous articles have used EL to bind instances to containers.
<div id="root">
<h1>Hello,{{name}}</h1>
</div>
<script>
// Create a vue instance
new Vue({
el: '#root'.// Write as an object
data: {
name: 'Sun Shangxiang',}})</script>
Copy the code
The second way to write it
We’re not going to use el in the example now. Let’s first print a vUE instance to see
const newVue = new Vue({
data: {
name: 'Sun Shangxiang',}})console.log(newVue)
Copy the code
All the bands in the red box$
Properties are for programmers. Don’t take$
It’s all used at the bottom.
What we’re going to use now is not the instance, but the creator of the instance, the method on its prototype object. The following figure
newVue.$mount('#root')
Copy the code
$mount can also specify containers.
data
The first way to write it
Object type
data:{
name:'yyds'
}
Copy the code
The second way to write it
functional
And the function must have a return value. Only functional writing can be used in components.
new Vue({
el: 'root'.data: function () {
return {
name: 'Sun Shangxiang',}}})Copy the code
Is 🤔 the function we call?
No, it is called by an instance of Vue. So let’s take a look at the current this reference to this function.
new Vue({
el: 'root'.data: function () {
console.log(this."this")
return {
name: 'Sun Shangxiang',}}})Copy the code
You can see that the current this points to an instance of Vue
🤔 let’s write normal functions instead of arrow functions
new Vue({
el: 'root'.data :() = > {
console.log(this."this")
return {
name: 'Sun Shangxiang',}}})Copy the code
You can see that the current this pointer has changed to window. Since the arrow function doesn’t have its own this, it finds its outer this.
We can’t use arrow functions
The last
- There are two ways to write el:
-
Configure the EL attribute when new VueCopy the code
-
Create the vue instance first, then bind the value of el via vm.$mount('#root')Copy the code
- Two ways to write data
-
Object typeCopy the code
-
Functional component writing must use this, otherwise an error is reportedCopy the code
-
An important principle
For functions managed by Vue, do not write arrow functions. If you do, this will no longer be a Vue instance.Copy the code