The difference between template and el in vue & the process of extracting template step by step into vue components


1 Introduction

We want to integrate Vue in the webpack environment, so we must have dependencies on it, so we need to install it first

  • Because we will also use vue in actual projects in the future, we are not dependent on development, we should use it --save, not--save-dev
  • installation: npm install vue --save

Code directory structure, the demo code of this blog has a download link at the bottom of the page (~ ̄▽ ̄)~
Insert picture description here


2. Code Demo

2.1 The relationship between el and template

index.html file

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>测试</title>
</head>
<body>

<div id="app">
  <h2>{
   
   {message}}</h2>
  <button @click="btnClick">按钮</button>
</div>

</body>
<script src="./dist/bundle.js"></script>
</html>

main.js file

//使用vue进行开发
import Vue from 'vue'

let app = new Vue({
    
    
  el: '#app',
  data:{
    
    
    message:'hello world'
  },
  methods:{
    
    
    btnClick() {
    
    
      console.log('---');
    }
  }
})

After normal operation, let's consider another question:

  • If we want to display the data in data in the interface, we must modify index.html
  • If we customize the component later, we must also modify index.html to use the component
  • But in the future development of the html template, I don't want to manually modify it frequently. Can it be done?

Defined templateattributes:

  • Vue in previous examples, we define the elattributes for the index.html and #appafter binding, so that Vue instance can manage the content of which it
  • Here, we can delete the content of the div element in the index.html file, leaving only a basic div element with the app id
  • But if I still want to display the content of { {message}}, what should I do?
  • We can define another template attribute, the code is as follows:
let app = new Vue({
    
    
  el: '#app',
  template: `
    <div>
      <h2>{
     
     {message}}</h2>
      <button @click="btnClick">按钮</button>
    </div>
  `,
  data: {
    
    
    message: 'hello world'
  },
  methods: {
    
    
    btnClick() {
    
    
      console.log('---');
    }
  }
})

Repack, run the program, and display the same result and HTML code structure as before.

So, what is the relationship between el and template?

  • el is used to specify the DOM to be managed by Vue, which can help to parse the instructions, event monitoring, and so on.
  • And if the template is also specified in the Vue instance, the content of the template template will replace the mounted corresponding el template.

As shown in the animation below: the content of the template template will replace the mounted template corresponding to el

Insert picture description here
What are the benefits of doing this? The answer is: after doing this, we don’t need to manipulate index.html again in future development, just write the corresponding tags in the template.

2.2 Further extraction optimization

For the above code, it is very troublesome to write the template module, what should I do?

Using the idea of ​​componentization, we can extract the content in the template.

main.js

//使用vue进行开发
import Vue from 'vue'

// 1.抽离出一个组件
let App = {
    
    
  template: `
    <div>
      <h2>{
     
     {message}}</h2>
      <button @click="btnClick">按钮</button>
    </div>
  `,
  data() {
    
    
    return {
    
    
      message: 'hello world'
    }
  },
  methods: {
    
    
    btnClick() {
    
    
      console.log('---');
    }
  }
}

let app = new Vue({
    
    
  el: '#app',
  template: '<App></App>', // 3.使用
  components:{
    
     // 2.在Vue根实例中进行注册
    App
  }
})

2.3 Extract into js file again

We can also extract the following code into a js file and export it.

Create an app.js file

export default {
    
    
  template: `
    <div>
      <h2>{
     
     {message}}</h2>
      <button @click="btnClick">按钮</button>
    </div>
  `,
  data() {
    
    
    return {
    
    
      message: 'hello world'
    }
  },
  methods: {
    
    
    btnClick() {
    
    
      console.log('---');
    }
  }

Then introduce it in the main.js file

//使用vue进行开发
import Vue from 'vue'

import App from './vue/app'

let app = new Vue({
    
    
  el: '#app',
  template: '<App></App>',
  components:{
    
    
    App
  }
})

2.4 Continue to extract into .vue files

But in the code above, it is very inconvenient to organize and use a component in the form of a js object

  • On the one hand, writing the template module is very troublesome
  • On the other hand, if there is a style, where should we write it?

Now, we have a new way to organize the components of a vue: Create a App.vuefile
Insert picture description here
App.vue file

<template>
  <div>
    <h2 class="title">{
    
    {
    
    message}}</h2>
    <button @click="btnClick">按钮</button>
  </div>
</template>

<script>
  export default {
    
    
    name: "App",
    data() {
    
    
      return {
    
    
        message: 'hello world'
      }
    },
    methods: {
    
    
      btnClick() {
    
    
        console.log('---');
      }
    }
  }
</script>

<style scoped>
  .title {
    
    
    color: red;
  }
</style>

Import in the main.js file

import Vue from 'vue'

// import App from './vue/app'
import App from './vue/App.vue' //注意需要加 .vue 后缀

let app = new Vue({
    
    
  el: '#app',
  template: '<App></App>',
  components:{
    
    
    App
  }
})

Repackaged and reported an error. Tip We need a proper loader to handle the .vuefiles
Insert picture description here
installed vue-loaderandvue-template-compiler

npm install vue-loader vue-template-compiler --save-dev

  • vue-loader is a webpack loader, which allows you to write Vue components in a format called Single File Components (SFCs).
  • vue-template-compiler compiles vue files

Configuration

// webpack.config.js

module.exports = {
    
    
  module: {
    
    
    rules: [
      // ... 其它规则
      {
    
    
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]
  }
}

I found an error again after repackaging: provide us with vue-loader and we need a plug-in to work with it.
Insert picture description here
Reason: The version of vue-loader I installed is 15.9.6, and the vue official website wrote: Vue Loader v15 now needs a webpack plug-in to use it correctly . The configuration of Vue Loader is different from other loaders. In addition to applying vue-loader to all files with a .vue extension through a rule, make sure to add the Vue Loader plugin in the webpack configuration VueLoaderPlugin.

This plugin is a must! Its responsibility is to copy and apply other rules you have defined to the corresponding language blocks in the .vue file. For example, if we have a matching /\.js$/rule, then it applies to .vuedocuments in the <script>block.

// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
    
    
  // ...
  
  plugins: [
    // 请确保引入这个插件来施展魔法
    new VueLoaderPlugin()
  ]
}

Repack, normal!

2.5 How to omit the suffix when importing vue files

// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
    
    
  // ...
  
 resolve: {
    
    
    extensions:['.js','.vue','.css'] //加一条配置
  }
}

3. Some information

vue official website | what is vue-loader

vue official website | introduction of el and template

https://www.cnblogs.com/vickylinj/p/10941112.html

Demo code download link: https://webchang.lanzous.com/i9bBNkgdnre Password: 34bq

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/112688479