Problems encountered when encapsulating global components Vue3

Preface:
A simple encapsulation component of a query is made, and the page looks like this
insert image description here
Code:

1.在公共组件的文件中创建了一个叫Search.vue的文件
<template>
  <div>
    <van-search v-model="searchVal" show-action :placeholder="placeholder">
      <template #action>
        <div @click="onClickButton">搜索</div>
      </template>
    </van-search>
  </div>
</template>
<script setup name="Search">
// 必须先声明
const emit = defineEmits();
const props = defineProps({
    
    
  placeholder: {
    
    
    type: String,
    default: "请输入",
  },
});
const searchVal = ref('');
function onClickButton() {
    
    
 emit("getSearchVal", searchVal.value)
}
defineExpose({
    
     onClickButton})

// 将子组件的方法暴露给父组件
</script>

2. components文件下新增index.js (这么写 方便以后有更多的公共组件, 统一维护在此文件夹)
用来引入上边创建的Search.vue文件
import Search from "./Search.vue";
export default {
    
    
  install(app) {
    
    
    app.component(Search.name, Search);
  },
};

3. The result of the above file is like this
insert image description here

4. Introduce the index.js file under (2) step in main.js

(也可以在mian.js文件中直接引入, 这里考虑到日后可能还会有其他的公共组件, 所以写在了index.js中,看起来不会乱~)
import components from "@/components"; // 公共组件
app.use(components)

The above globally available component has been created and
introduced in the required file.

 <search ref="searchRef" @getSearchVal="getSearchVal" placeholder="请输入人员姓名或工号"></search>
<script setup name="AddPeople">
const searchRef = ref(null);
function getSearchVal(val) {
    
    
  console.log(val, 'search组件中的值');
}
</script>

Guess you like

Origin blog.csdn.net/weixin_42792519/article/details/127633114