Vue 父组件向子组件传值并修改子组件的图片路径

一、使用props:{...}

该方式可以实现父组件向子组件传值的同时还可以修改子组件的图片路径

Son.vue

<template>
  <div class="Introduce">
    <div class="Intro_img">
    //动态修改图片路径
      <img :src="src" class="DPerson_1" />
    </div>
    <div class="Intro_info">
    //动态修改值
      <h1>{
    
    {
    
     IntroTitle }}</h1>
      <p>
        {
    
    {
    
     IntroInfo }}
      </p>
    </div>
  </div>
</template>
<script>
export default {
    
    
  name: "Introduce",
  props: {
    
    
    IntroTitle: String,
    IntroInfo: String,
    src: {
    
    
      type: String,
      require: true,
    },
  },
};
</script>

Father.vue

<template>
	<Introduce :IntroTitle="title" :IntroInfo="message" :src="src"></Introduce>
</template>
<script>
export default {
    
    
  name: "Main",
  components: {
    
    
    ADInfo,
    Title,
    Introduce,
  },
  data() {
    
    
    return {
    
    
      message: "haha",
      title: "Way",
      src: require('@/...(图片路径)'),
    };
  },
};
</script>

这里要注意,传图片路径的时候,require(’ … ')的括号中要用单引号,外层用双引号包裹

二、使用props:[" "," ",...]

如果不需要同时动态修改图片路径,则用该方式实现父组件向子组件传值;

Son.vue

<template>
  <div class="Introduce">
    <div class="Intro_info">
    //动态修改值
      <h1>{
    
    {
    
     IntroTitle }}</h1>
      <p>
        {
    
    {
    
     IntroInfo }}
      </p>
    </div>
  </div>
</template>
<script>
export default {
    
    
  name: "Introduce",
  //用法如下:
  props: ["IntroTitle", "IntroInfo"],
  },
};
</script>

Father.vue

<template>
	<Introduce :IntroTitle="title" :IntroInfo="message"></Introduce>
</template>
<script>
export default {
    
    
  name: "Main",
  components: {
    
    
    ADInfo,
    Title,
    Introduce,
  },
  data() {
    
    
    return {
    
    
      message: "haha",
      title: "Way",
    };
  },
};
</script>

参考文章

https://blog.csdn.net/meoncih_/article/details/107647809

Guess you like

Origin blog.csdn.net/weixin_46353030/article/details/121755051