2021/1/20 vue模块化,vue组件,vue生命周期函数,vue-resource请求数据,Axios 请求数据,Vue父组件给子组件传值,vue子父组件互相取值
vue模块化
vue把相似功能的方法和数据,统一保存在一个模块中,方便反复调用。
/*定义模块 */
var storage = {
set(key,value){
localStorage.setItem(key, JSON.stringify(value))
},
get(key){
return JSON.parse(localStorage.getItem(key))
},
remove(key){
localStorage.removeItem(key)
}
}
/*暴露模块 */
export default storage
在使用处引入模块
<script> import storage from './model/storage.js' </script>
vue组件
组件生成:在src目录下创建components文件夹,在文件夹内定义需要的xx.vue文件,引入<template>后,定义一个根容器,任何模块必须引入根容器。
组件引入:在<script>目录中通过 import xxx from './components/xxx.vue'引入组件,在暴露data()同级方法下,创建components模块目录,通过 'v-xxx':xxx来定义组件名称
组件载入:在父组件<template>中,引入<v-xxx></v-xxx>的方式引入组件名称
vue生命周期函数
beforeCreate() {
console.log('实例创建之前1')
},
created() {
console.log('实例创建完成2')
},
beforeMount() {
console.log('模板编译之前3')
},
mounted() { /*请求数据,操作dom,放在这,mounted*/
console.log('模板编译完成4')
},
beforeUpdate() {
console.log('数据更新之前')
},
updated() {
console.log('数据更新之后')
},
beforeDestroy() { /*页面销毁的时候要保存一些数据,就可以监听这个销毁的生命周期函数 */
console.log('实例销毁之前')
},
destroyed() {
console.log('实例销毁完成')
},
vue-resource请求数据
vue-resource包导入:cmd到项目目录下,通过 cnpm install vue-resource --save 引入包
vue-resource包导入项目:在main.js目录下,import VueResource from 'vue-resource', Vue.use(VueResource)
vue-resource请求数据:this.$http.get(url).then((response) =>{},(error)=>{})
Axios请求数据
Axios包导入:cmd到项目目录下,通过 cnpm install Axios --save 引入包
Axios包导入项目:在使用位置<script>目录下 import Axios form 'axios'
Axios请求数据:Axios.get(url).then((response)=>{}).catch()=>{})
vue父组件给子组件传值
在父组件的 子组件引入 <v-xxx :msg="msg"></v-xxx>
在子组件创建props方法,可以是props:['msg'],也可以是props:['masg':String] 传入数据并验证数据类型,然后在表单中直接引入{{msg}}即可引入父组件数据
子父组件互相主动取值
父组件调用子组件数据:
在表单中 <v-xxx ref = "xx"></v-xxx>定义ref节点,通过this.$refs.xx.子组件属性(子组件方法)主动调用子组件属性和方法
子组件调用父组件数据
在子组件方法中,通过this.$parent.父组件属性(父组件方法)直接引用父组件属性和方法

浙公网安备 33010602011771号