本文将讲解如何利用 Vue.js 中的 el-select 标签根据下拉框选项的不同,展示不同的内容界面,并提供完整的代码示例。

实现步骤:

  1. 首先需要引入 el-select 组件。
  2. 在父组件中定义一个变量来表示当前选中的下拉框选项。
  3. 在 el-select 标签中绑定一个 change 事件,当选项改变时,将选中的值赋值给变量。
  4. 根据不同的选项值,展示不同的内容界面。
  5. 将展示不同内容的代码封装成一个子组件,根据选中的值来动态渲染子组件。
  6. 在父组件中引入子组件,并将选中的值传递给子组件。
  7. 在子组件中根据传递的值展示不同的内容。

示例代码:

父组件:

<template>
  <div>
    <el-select v-model="selected" @change="handleChange">
      <el-option label='选项1' value='1'></el-option>
      <el-option label='选项2' value='2'></el-option>
      <el-option label='选项3' value='3'></el-option>
    </el-select>
    <div v-if="selected === '1'">
      <child-component-1></child-component-1>
    </div>
    <div v-if="selected === '2'">
      <child-component-2></child-component-2>
    </div>
    <div v-if="selected === '3'">
      <child-component-3></child-component-3>
    </div>
  </div>
</template>

<script>
import ChildComponent1 from './ChildComponent1.vue'
import ChildComponent2 from './ChildComponent2.vue'
import ChildComponent3 from './ChildComponent3.vue'

export default {
  components: {
    ChildComponent1,
    ChildComponent2,
    ChildComponent3
  },
  data () {
    return {
      selected: ''
    }
  },
  methods: {
    handleChange (value) {
      this.selected = value
    }
  }
}
</script>

子组件:

<template>
  <div>
    <h1>{{ title }}</h1>
    <p>{{ content }}</p>
  </div>
</template>

<script>
export default {
  props: {
    selected: {
      type: String,
      required: true
    }
  },
  computed: {
    title () {
      if (this.selected === '1') {
        return '选项1的标题'
      } else if (this.selected === '2') {
        return '选项2的标题'
      } else if (this.selected === '3') {
        return '选项3的标题'
      } else {
        return ''
      }
    },
    content () {
      if (this.selected === '1') {
        return '选项1的内容'
      } else if (this.selected === '2') {
        return '选项2的内容'
      } else if (this.selected === '3') {
        return '选项3的内容'
      } else {
        return ''
      }
    }
  }
}
</script>

通过以上代码,我们可以实现根据 el-select 选择的不同选项展示不同的内容界面,并通过子组件封装代码,使代码结构更加清晰易懂。


原文地址: https://www.cveoy.top/t/topic/oiXC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录