本文主要是介绍vue3 onMounted的坑,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
onMounted的坑
当放在return后面
只显示onmounted里面的函数
<template><h1>我是Vue3</h1><h2>name:{{name}}</h2><h2>age:{{age}}</h2><h2>{{position.age}}</h2><h2 v-show="position.p">{{position.p}}</h2><h2 v-show="position.sex">{{position.sex}}</h2><button @click="sayhello">sayhello</button><button @click="tellposition">position</button><button @click="addsex">添加一个sex属性</button><button @click="deletename">删除name属性</button><hr><h2>当前点击时鼠标的坐标为{{point.x}}-{{point.y}}</h2>
</template><script>import {ref,reactive,onMounted} from 'vue'
export default {name: 'App',setup(){let name=ref("张三");let age=ref(18);let point=reactive({x:0,y:0})let position=reactive({p:"engineer",age:18})function sayhello(){alert(name.value+age.value)}function tellposition(){console.log(position),position.p="ui"position.age=19}function addsex(){position.sex="nu"}function deletename(){delete position.p}return{name,age,sayhello,position,tellposition,addsex,deletename,point},onMounted(()=>{window.addEventListener('click',(event)=>{point.x=event.pageX;point.y=event.pageY})})}}
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>
所以onMounted得放在return前面
<template><h1>我是Vue3</h1><h2>name:{{name}}</h2><h2>age:{{age}}</h2><h2>{{position.age}}</h2><h2 v-show="position.p">{{position.p}}</h2><h2 v-show="position.sex">{{position.sex}}</h2><button @click="sayhello">sayhello</button><button @click="tellposition">position</button><button @click="addsex">添加一个sex属性</button><button @click="deletename">删除name属性</button><hr><h2>当前点击时鼠标的坐标为{{point.x}}-{{point.y}}</h2>
</template><script>import {ref,reactive,onMounted} from 'vue'
export default {name: 'App',setup(){let name=ref("张三");let age=ref(18);let point=reactive({x:0,y:0})let position=reactive({p:"engineer",age:18})function sayhello(){alert(name.value+age.value)}function tellposition(){console.log(position),position.p="ui"position.age=19}function addsex(){position.sex="nu"}function deletename(){delete position.p}onMounted(()=>{window.addEventListener('click',(event)=>{point.x=event.pageX;point.y=event.pageY})})return{name,age,sayhello,position,tellposition,addsex,deletename,point}}}
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>
这篇关于vue3 onMounted的坑的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!