vue3中ref

1.定义一个响应式数据


2.ref获取元素

2.1 获取子组件值

  • App.vue
<template>
  <div>
    <!-- 不知什么原因:@click一开始怎么都没法触发点击事件 -->
    <button @click="show()">click-button----{{count}}</button>
    <Dialog ref="dialog"></Dialog>
  </div>
</template>

<script>
import { reactive,toRefs,ref } from "vue";
import Dialog from "./components/Dialog.vue";
export default {
  components: {
    Dialog,
  },
  setup() {
    const state = reactive({
      count: 0,
    });
     
    const dialog = ref(null);//不要忘记return出去,要么获取不到值
    //显示子组件
    const show = () => {
      console.log('---click,show');
      //调用dialog组件里面的showDialog方法
      dialog.value.showDialog();

      dialog.value.count += 1000; //-能自己修改组件里面的值
      console.log(dialog.value)   // 返回proxy对象
    };

    return {
      ...toRefs(state),
      show,
      dialog
    };
  },
};
</script>

<style lang="scss" scoped></style>

  • components/Dialog.vue
<template>
  <div>
    <div class="content" v-if="show">dialog:{{ count }}</div>
  </div>
</template>

<script>
import { reactive, toRefs, ref } from "vue";
export default {
  setup() {
    const state = reactive({
      count: 0,
    });
    const show = ref(false);
    const showDialog = () => {
      show.value = true;
      state.count++;
    };
    const fadeDialog=()=>{
      show.value = false;
    }
    return {
      ...toRefs(state),//----state中的count可以直接在view中展示了;
      show,
      showDialog,
      fadeDialog
    };
  },
};
</script>
<style lang="scss" scoped></style>

2.2 获取标签元素

  • 功能需求: 让输入框自动获取焦点
<template>
  <h2>App</h2>
  <input type="text" ref="inputRef" />
</template>

<script>
import { onMounted,ref } from 'vue'
export default {
  setup() {
    const inputRef = ref(null)
    onMounted(() => {
      inputRef.value && inputRef.value.focus()
    })

    return {
      inputRef
    }
  }
}
</script>
博文有错,可以修改组件里面的值内容;
posted @ 2023-03-10 10:47  盘思动  阅读(53)  评论(0编辑  收藏  举报