Vue学习笔记[10]-在webpack中初步配置vue

安装:

npm install vue --save
<!--html-->
<body>
  <div id="app"></div>
</body>
<script src="./dist/boundle.js"></script>
//main.js
import Vue from 'vue'
new Vue({
  el:'#app',
  template:`
 <div>
 <h1>{{message}}<h1>
 </div>
  `,
  data:{
    message:'hi Vue !'
  }
})

当el和template同时存在时,vue会将template中的内容替换掉el的内容.
此时默认使用runtime-only build of Vue,因此无法在html中加载模板,需要配置webpack.config.js:

const path = require('path') //导入node中的path包
module.exports = {
  entry: "./src/main.js",
  output: {...},
  module: {...},
  resolve:{
    alias:{
      'vue$':'vue/dist/vue.esm.js'
    }
  }
}

初步抽离成组件:

import Vue from 'vue'

const App = {
  template: `
  <div>
 <h1>{{message}}<h1>
 </div>
  `,
  data() {
    return {
      message: 'hi Vue !'
    }
  }
}
new Vue({
  el: '#app',
template:"</App>"
  comments:{
    App,
  }
})

再进一步抽离:

//app.js
export default const App = {
  template: `
  <div>
 <h1>{{message}}<h1>
 </div>
  `,
  data() {
    return {
      message: 'hi Vue !'
    }
  }
}
//main.js
import Vue from 'vue'
import App from './vue/app'
new Vue({
  el: '#app',
template:"</App>"
  comments:{
    App,
  }
})

抽离出.vue文件:

1.安装 vue-loader 和 vue-template-compiler

cnpm install vue-loader@13.0.0 vue-template-compiler --save --dev

TODO:版本(这里vue-loader使用最新版本出了意外...因此使用了较低版本后续补充最新版本):

{
"vue-loader": "^13.0.0",
"vue-template-compiler": "^2.6.10"
}
//App.vue
<template>
  <div>
    <h2>{{message}}</h2>
  </div>
</template>

<script>

  export default {
    name:"App",
    data() {
      return {
        message: "hello Vue!"
      }
    },
  }
</script>

<style scoped>
h2 {
  color: red;
}
</style>
//main.js
import Vue from 'vue';
import App from "./vue/app.vue";
new Vue({
  el: '#app',
  template:'<App/>',
  components:{
    App,
  }
})
<!-- index.html -->
<body>
  <div id="app"></div>
</body>
<script src="./dist/boundle.js"></script>

在vue文件中的style标签上,有一个特殊的属性:scoped。当一个style标签拥有scoped属性时,它的CSS样式就只能作用于当前的组件,也就是说,该样式只能适用于当前组件元素。通过该属性,可以使得组件之间的样式不互相污染。如果一个项目中的所有style标签全部加上了scoped,相当于实现了样式的模块化。

父子组件

//Child.vue
<template>
  <div>
    <button @click="num++"> + </button>
  </div>
</template>

<script>
  export default {
    name:"Child",
    data() {
      return {
        num: 0,
      }
    },
  }
</script>

<style scoped>

button {
  width: 80px;
  height: 80px;
}
</style>
//App.vue
<template>
  <div>
    <h2>{{message}}</h2>
    <Child/> //在此处使用
  </div>
</template>

<script>
import Child from './Child.vue';
  export default {
    components:{Child},//在此处注册
    name:"App",
    data() {
      return {
        message: "hello Vue!"
      }
    },
  }
</script>

<style scoped>
h2 {
  color: red;
}
</style>

在webpack.config.js的module.exports ={...,resolve:{...}}中添加extension:['.js','.css','.vue']后可省略导入时的后缀.import Child from './Child';

目前的文件结构
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。