济南建网站公司报价seo优化网站的手段
1.props/defineProps
使用场景:
一般当父组件需要给子组件传值的时候会用到。
Vue2:props
vue2在父组件里引入子组件以后需要在components里面注册后再使用;
父组件
<son-compnents :info=info></son-components>import SonCompnents from "./cpmponents/SonCompnents.vue"components: {SonCompnents,},data(){return {info:'个人信息'}}
子组件
props:['info'] //数组写法
props:{info:Stirng //对象写法
}
Vue3:defineProps
vue3的父组件引用后直接使用即可;
父组件
<son-compnents :info=info></son-components>import SonCompnents from "./cpmponents/SonCompnents.vue"
import {ref }from 'vue'
let info = ref('props传参')
子组件
<script setup>
import {ref,computed} from 'vue'
const props = defineProps({info:String
})
一般props的值就用computed来接收使用
let getInfo = computed(()=>{return props.info
})
</script>
2. emit/defineEmits
使用场景:
用于子组件向父组件传递信息,修改父组件传的props的值
Vue2:emit
子组件
<button @click="sendMes(name)">点击向父组件传值</button>data(){return{name:'子组件'}}methods:{sendMes(name){this.$emit('getMes',name) 触发父组件绑定的getMes事件从而触发对应的方法,后面是传的参数}
}
父组件<son-componet @getMes="changeMes"></son-componet>import SonComponet from '@/components/SonComponet'data(){return(){name:'原本的值'}}methods:{changeMes(name){this.name=name}}
Vue3:defineEmits
子组件
<el-button @click="sendMes">子组件给父组件传值</el-button>const emits = defineEmits(["close"]);
const sendMes = ()=>{emits("close","传的参数") //可传可不传
}
父组件<son-component @close= "changeMes"></son-component>import SonComponent from '@/components/SonComponent.vue'
import {ref} from 'vue'let mes = ref('原值')
const changeMes = (name)=>{mes.value = name }
3.watch
使用场景:
用于对数据的监听并实时做出处理;
Vue2:watch
子组件
1.监听对象的一个属性值并实时修改另一个值watch: {'form.currency': {handler(newValue, oldValue) {if (newValue == 'USD') {this.currencyType = '万美元';} else {this.currencyType = '万元';}},deep: true,},'form2.currency': {handler(newValue, oldValue) {if (newValue == 'USD') {this.currencyType = '万美元';} else {this.currencyType = '万元';}},deep: true}},
Vue3:watch
这里的场景是子组件是弹窗,父组件是表格,在表格中引入,点击编辑,子组件弹出框的数据随之更改;
子组件
import {ref,watch} from 'vue'const props = defineProps({info:Obeject
})
let info = ref({})当监听的值是一个对象的某个属性值时,watch的第一个参数就需要写成函数,其他直接写参数即可
watch(()=>props.info //如果只是子组件本身的一个值 name,(newValue,oldValue)=>{if(newValue){form = {name = newValue.nameprice= newValue.price}} },{ 第三个对象配置watch的属性deep:true}
)
Vue3:watchEffect
watchEffect的作用是不需要指定需要监听的属性,而是监听一个回调,当回调内所使用的数据发生变化时,回调就会执行;
缺点:1.不会立刻执行(可用immediate)解决;2.获取不到newValue和oldValue;
更多知识点得参考其他教程
import {watchEffect,ref} from 'vue'
let a = ref(1)
let b = ref(1)const stop =watchEffect(()=>{console.log(a,b) 一但a或b的值发生了改变,这个打印函数就会执行 })