目录
入门
6月22日开始学习Vue,总的来说感觉这是一个比较好上手的框架。
但是刚刚遇到一个坑,在使用router-link组件给:to传一个对象时,发现不能生成正确的路径。
打开Chrome调试工具,看到下面这一行 ,我的标签是这样写的<router-link :to="{name:'sign-up'}">,在我的Router对象routes数组是这样写的{path: '/sign-up', name: 'SignUp', component: SignUp}。
开始百思不得解(其实我一直没搞懂这些配置每一个属性的意义,官方文档好像也没有详细的介绍),看官方示例https://github.com/vuejs/vue-router/blob/dev/examples/named-routes/app.js发现自己代码唯一不同就是name与path值写得不一致。
那么只有两种可能的情况:
- path与name的值要保持一致。
- :to中传递的对象name属性对应的其实是routes里的name而不是path。
第一种情况很快排除了,因为之前给to传静态值的时候我的routes也是这么写的,于是我把:to="{name:'sign-up'} 改成了 :to="{name:'Sign'},果不其然,这次生成了正确的路径!
Vuex
几天前在考虑如果多个组件需要共享一份数据该怎么实现,官方推荐了以下做法:
可以简单地通过维护一份数据来实现共享:
const sourceOfTruth = {} const vmA = new Vue({ data: sourceOfTruth }) const vmB = new Vue({ data: sourceOfTruth })
现在当
sourceOfTruth
发生变化,vmA
和vmB
都将自动的更新引用它们的视图。子组件们的每个实例也会通过this.$root.$data
去访问。现在我们有了唯一的数据来源,但是,调试将会变为噩梦。任何时间,我们应用中的任何部分,在任何数据改变后,都不会留下变更过的记录。为了解决这个问题,我们采用一个简单的 store 模式:
var store = { debug: true, state: { message: 'Hello!' }, setMessageAction (newValue) { if (this.debug) console.log('setMessageAction triggered with', newValue) this.state.message = newValue }, clearMessageAction () { if (this.debug) console.log('clearMessageAction triggered') this.state.message = '' } }
接着就看到原来早就有比较成(fang)熟(bian)的处理方式:Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
安装:
npm install vuex --save
接着导入模块,在src目录下创建store文件夹,新建index.js文件,写上以下代码:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
state: {
},
modules: {
},
strict: debug,
getters: {
}
})
找到main.js文件,引入store模块, import store from './store', 然后插入到Vue对象中就可以使用了
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
Vue.use(ElementUI);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>',
// render: h => h (App)
})
如何让Vue项目打包后显示favicon?
- 在static目录下,创建一个名为img的文件夹用来保存图片,将准备好的favicon.ico文件添加到这个目录下,
找到build/webpack.prod.conf.js文件,找到如下代码:
new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', inject: true,
插入一行:
new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', inject: true, favicon: 'static/img/favicon.ico', //加入这行 // 也可以这样写:favicon: path.resolve('static/img/favicon.ico')
-
重新打包项目:
npm run build
大功告成!
- 需要注意的是:build目录下有一个webpack.dev.conf.js文件,作用跟上面这个文件类似,这个文件事实上是开发环境下的配置,改了这里只能在本地服务器看到favicon效果,而打包后的项目仍然不能正常引用favicon.ico文件。
解决vue-router配置history模式生产环境下刷新404的问题
history模式可以解决烦人的“#”,这种模式下URL的hash就跟正常访问一一样,可是部署到服务器上直接访问如:http://oursite.com/user/id 就会出现404错误,好在官方提供了解决方案,https://router.vuejs.org/zh/guide/essentials/history-mode.html
我的服务器是Nginx,所以需要在nginx配置文件加上这几行,配置完之后果然404错误消失了!
location / {
try_files $uri $uri/ /index.html;
}