首页 > 解决方案 > 如何在 Javascript/Vue 中创建双 IF 条件?

问题描述

在这个例子中,我访问运行时函数两次,第一次函数正常工作,第二次它用来自模板 2 的数据替换模板 1。

帮助我们解决这个问题。

<template>
  <div>

<v-runtime-template :template="template1"></v-runtime-template>
<v-runtime-template :template="template2"></v-runtime-template>

  </div>
</template>


<script>
import VRuntimeTemplate from "v-runtime-template";
import axios from 'axios'
export default {

    data: () => ({
      x: 0, y: 0,
            template: null,
      template1: null,
      template2: null,
    }),
    components: {
    VRuntimeTemplate,
  },

    mounted() {
        let vm = this
    vm.runtime();

    },
    methods: {

    runtime(){
        /*  if the condition is correct assign
range of indexes of the second block */
      if (this.x == -1){this.x = 11; this.y = 24;}

        /*  and if this condition is correct we assign
         index range of the first block */
      if (this.x == 0){this.x = -1; this.y = 12;}

this.template = `
    <div class="row justify-content-center">
      <div v-for="(mult, index) in mults">
         <div v-if="(index > x & index < y)">
            <div class="card">
            <!--       -->
            </div>
        </div>
      </div>
    </div>`;

    /* find out which block was formed
         and assign the generated block to the first one
         or the second template */
if (this.x == 11){this.template2 = this.template;}
if (this.x == -1){this.template1 = this.template;}

    /* there is an error here: I get two identical blocks */
    }
</script>

为什么当 x 为 11 时,条件 x == -1 为假,但满足?如何配置 IF 条件以使 template1 在第二次运行 runtime () 函数时不会发生变化?

标签: javascriptvue.js

解决方案


在 js&中用于按位与

console.log(3 & 5);
console.log(0b11 & 0b101);

你想要的是布尔 AND,在 js 中是&&

console.log(true && false);
console.log(true && true);


推荐阅读