vue3.X简单使用

vue3.X

信息源:Wscats/vue-cli
个人喜欢的前端博客:技术胖,包含多种前端前沿技术

脚手架搭建

npm install -g @vue/cli
vue create katsuki-test  //进入配置选择,选3版本

根据选择的管理包运行
yarn serve
npm run serve

setup(props, ctx)

setup对应生命周期beforeCreatecreated

接受的参数
props:获取父组件等传入值或函数
ctx包含的一些属性:

  • root
  • parent
  • refs
  • attrs
  • listeners
  • isServer
  • ssrContext
  • emit

setup做什么?
1.创建响应式数据:refreactive,非响应式,相当于state
2.定义函数
3.引入的方式调用生命周期
4.return响应数据和函数,template能调用

生命周期

setup取缔了2.0beforeCreatecreated生命周期

Vue2.0Vue3.0
beforeCreatesetup
createdsetup
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeDestroyonBeforeUnmount
destroyedonUnmounted
errorCapturedonErrorCaptured

新增了onRenderTrackedonRenderTriggered

使用案例

案例一:ref

<template>
  <div>
	<button @click="onChange">{{ name }} age: {{ age }}</button>
  </div>
</template>
<script>
  import { ref } from 'vue'
  export default {
  	// 第一个参数接收props
  	setup() {
  		// 响应式数据
		let name = ref('katsuki')
		let age = ref(17)
		// 函数
		const onChange = () => age.value ++
		//必须返回 模板中才能使用
		return {
			name,
			age,
			onChange
		}
	} 
  }
</script>

案例二:emit、state

<template>
    <input type="text" v-model="username" placeholder="Username" />
    <input type="password" v-model="password" placeholder="Password" />
    <button @click="login">假登录</button>
    <p>Values: {{ lowerCaseUserName + ' ' + password }}</p>
</template>
<script>
  // 引入需要使用的生命周期
  import { reactive, computed, onMounted, toRefs } from 'vue'
  export default {
  	emits: {
    	// 对应名称接收消息
    	login: obj => {
      		console.log('obj', obj)
      		return true
    	}
  	},
  	// 第二个参数接收emit
  	setup(props, { emit }) {
  		// 响应数据集合state
		const state = reactive({
	      username: '',
	      password: '',
	      lowerCaseUserName: computed(() => state.username.toLowerCase()),
	    })
	    
	    // 发送消息
	    const login = () => {
	      emit('login', {
	        username: state.username,
	        password: state.password,
	      })
	    }
		
		onMounted(() => {
	      console.log('onMounted')
	    })
	    
	    return {
	      ...toRefs(state), // 解构转换为响应式框架
	      login,
	    }
	} 
  }
</script>

案例三:watch

Watch.vue
<template>
  <div>
    <div class="input_warp">
      <input type="text" v-model="inputValue" />
    </div>
    <div class="input_warp">
      <input type="text" v-model="inputValue2" />
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, watch } from 'vue'
export default {
  setup() {
    const state = reactive({
      inputValue: '',
      inputValue2: '',
    })
    // 监听单个值
    watch(() => state.inputValue, (newinputValue, oldinputValue) => {
      console.log('newinputValue', newinputValue)
      console.log('oldinputValue', oldinputValue)
    })
    // 监听多个值
    watch(
      () => [state.inputValue, state.inputValue2],
      ([newinputValue, newinputValue2], [oldinputValue, oldinputValue2]) => {
        console.log('newinputValue', newinputValue)
        console.log('newinputValue2', newinputValue2)
        console.log('oldinputValue', oldinputValue)
        console.log('oldinputValue2', oldinputValue2)
      }
    )
    return {
      ...toRefs(state),
    }
  },
}
</script>

<style lang="less">
.input_warp {
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;
  background-color: pink;
}
</style>

案例四:vuex

store/index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    inputValue: '',
    inputValue2: '',
  },
  getters: {
    getInputValue(state) {
      return state.inputValue
    },
    getInputValue2(state) {
      return state.inputValue2
    },
  },
  mutations: {
    setInputValue(state, value) {
      state.inputValue = value
    },
    setInputValue2(state, value) {
      state.inputValue2 = value
    },
  },
  actions: {},
  modules: {},
})

main.js添加引入

import store from './store'
createApp(App)
  .use(store)

Watch.vue

<template>
  <div>
    <div class="input_warp">
      <input type="text" v-model="inputValue" />
    </div>
    <div class="input_warp">
      <input type="text" v-model="inputValue2" />
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, watch } from 'vue'
import { useStore } from 'vuex'
export default {
  setup() {
  	const store = useStore()
    const state = reactive({
      inputValue: '',
      inputValue2: '',
    })
    watch(
      () => [state.inputValue, state.inputValue2],
      ([newinputValue, newinputValue2], [oldinputValue, oldinputValue2]) => {
      	// 奖数据存入store
        store.commit('setInputValue', newinputValue)
        store.commit('setInputValue2', newinputValue2)
        // 开启了eslint则必须调用
        console.log('oldinputValue', oldinputValue)
        console.log('oldinputValue2', oldinputValue2)
      }
    )
    return {
      ...toRefs(state),
    }
  },
}
</script>

<style lang="less">
.input_warp {
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;
  background-color: pink;
}
</style>

Panel.vue

<template>
  <div class="about">
    <Watch />
    <h3>inputValue:<span v-text="inputValue"></span></h3>
    <h3>inputValue2:<span v-text="inputValue2"></span></h3>
  </div>
</template>

<script>
import Watch from '../components/Watch'
import { reactive, toRefs, computed } from 'vue'
import { useStore } from 'vuex'
export default {
  components: {
    Watch,
  },
  setup() {
    const store = useStore()
    // 获取store的值,赋值到当前state中
    const state = reactive({
      inputValue: computed(() => {
        return store.getters.getInputValue
      }),
      inputValue2: computed(() => {
        return store.getters.getInputValue2
      }),
    })
    return {
      ...toRefs(state),
    }
  },
}
</script>

案例五:provide、inject

Father.vue

<template>
  <div>
  	FatherPage
    <Son />
  </div>
</template>

<script>
import Son from '../components/son'
import { provide, reactive } from 'vue'
export default {
  components: {
    Son,
  },
  setup() {
    const state = reactive({
      name: 'katsuki',
      arr: ['ォラォラォラォラ', '無駄無駄無駄', '貧弱貧弱貧弱', 'wryyyyyy', 'だが断る']
    })
	// 在父组件及其子组件中可获取
    provide('katsuki', state.name)
    provide('arr', state.arr)
  },
}
</script>

Son.vue

<template>
  <div>SonPage</div>
</template>

<script>
import { inject } from 'vue'
export default {
  setup() {
    const katsuki = inject('katsuki')
    console.log('katsuki', katsuki)
    const arr = inject('arr')
    console.log('arr', arr)
  },
}
</script>

案例六:hooks

src下创建hooks文件夹,在该文件夹下创建useNowTime.js

useNowTime.js

import { ref } from "vue";

const nowTime = ref("00:00:00");
const getNowTime = () => {
  const date = new Date();
  const h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  const m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  const s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  nowTime.value = h + ":" + m + ":" + s;
  setTimeout(getNowTime, 1000);
};

export { nowTime, getNowTime };
<template>
  <div>{{ nowTime }}</div>
  <div><button @click="getNowTime">显示时间</button></div>
</template>

<script>
import { nowTime, getNowTime } from "@/hooks/useNowTime";
export default {
  setup() {
    return {
      nowTime,
      getNowTime,
    };
  },
};
</script>

这样提取出来,就能在需要该功能的组件中引入,实现复用

案例七:获取元素dom(Vue2 Refs)

<template>
    <div ref="katsukiDivRef">ref元素</div>
    <el-table ref="elTbleRef"></el-table>
</template>

<script>
import { onMounted } from "vue";
import { ref } from "vue";
export default {
  setup() {
    const katsukiDivRef = ref();
    const elTbleRef = ref();
    onMounted(() => {
      console.log(katsukiDivRef)
      // element ui 调用函数
      console.log(elTbleRef.value.clearSelection)
    })
    return {
      katsukiDivRef,
      elTbleRef
    };
  },
}
</script>
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值