如何将 ref 传递给 props?

问题描述 投票:0回答:1
vue.js vuejs2
1个回答
0
投票

我不确定是否将其作为道具传递,但您始终可以在子组件中执行此操作。

console.log(this.$parent.$refs.target);

更多信息请参见文档


这是另一种做事方式(确实更干净)。

App.vue

<template>
  <div id="app">
    <div ref="target">target</div>
    <cmp :getScreenRef="() => $refs['target']" />
  </div>
</template>

<script>
import Cmp from "./components/cmp.vue";
export default {
  name: "App",
  components: {
    Cmp,
  },
};
</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>

cmp.vue

<template>
  <div>
    qwe <br />
    <button @click="logTarget">click me</button>
  </div>
</template>

<script>
export default {
  inheritAttrs: true,
  data() {
    return {
      screenRef: "",
    };
  },
  props: {
    getScreenRef: {
      type: Function,
      default: () => ({}),
    },
  },
  methods: {
    logTarget() {
      console.log("target:", this.screenRef);
    },
  },
  mounted() {
    this.screenRef = this.getScreenRef();
    this.$nextTick(function () {
      console.log("here?", this.screenRef);
    });
  },
};
</script>

归功于这个答案

© www.soinside.com 2019 - 2024. All rights reserved.