npm安装vue、vuex后如何与webpack结合使用

657 阅读1分钟

前言:

本来看着视频学着vuex的概念,老老实实地安装完vue和vuex,创建了index.htmlindex.js准备开开心心实践了:

npm install --save-dev vue
npm install --save-dev vuex
<body>
    <div id="app"></div>
    <script src="./index.js"></script>
</body>
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
const store=new Vuex.Store({
    state:{
        count:3
    }
})
new Vue({
    el:"#app",
    store,
    computed:{
        count(){
            return this.$store.state.count
        }
    }
})

打开html一看,发现报错了 image.png 翻译一下就是加载的vue包的入口文件是vue.runtime.common.js,而这个包的模板编译不可用。这个时候才恍然大悟自己忘记用webpack模块化了

webpack

npm init
npm install --save-dev  webpack webpack-cli

//vue编译
npm install --save-dev vue-loader vue-template-compiler

webpack-config.js配置

var VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
    entry: './index.js',
    plugins: [  
      new VueLoaderPlugin()
    ],
    module: {  
        rules: [
            { test: /\.vue$/, use: 'vue-loader' }
        ]
    },
    output: {filename: 'bundle.js'},
    mode:'development'
};

index.html

<body>
    <div id="app"></div>
    <script src="./dist/bundle.js"></script>
</body>

vuex先不用,先琢磨着插值能不能显示。index.js:

import Vue from 'vue';
import View from './View.vue'

new Vue({
    el:"#app",
    render:c=>c(View),
})

View.vue

<template>
    <div>{{msg}}</div>
</template>

<script>
export default {
    data(){
        return{
            msg:123
        }
    }
}
</script>

打包后打开html,显示了!

Vuex

ok重整旗鼓。正学到state核心概念之如何在 Vue 组件中获得 Vuex 状态

第一种方法:使用计算属性

//为了方便起见,我把store单独挑出来:store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)

export default new Vuex.Store({
    state:{
        count:3
    }
})

View.vue:引入store后使用计算属性就能访问了,这时打包后能在页面看到内容

<template>
    <div>{{count}}</div>
</template>

<script>
import store from './store'
export default {
computed: {
    count () {
      return store.state.count
    }
  }
}
</script>

第二种方法:store选项

Vuex 提供了一种机制将状态从根组件“注入”到每一个子组件中,即在根实例中注册 store 选项。这时候子组件可以通过 this.$store 访问到store。适合在有很多子组件的情况,这样就不用在子组件中频繁导入store了

//index.js
import View from './View.vue'
import Vue from 'vue';
import store from './store'

new Vue({
    el:"#app",
    store,
    render: c => c(View),
})

View.vue

<template>
    <div>{{count}}</div>
</template>

<script>
export default {
    computed: {
    count () {
      return this.$store.state.count
    }
  }
}
</script>

成功!继续加油!