Vuejs 代码在组件中不起作用,但在应用程序中起作用

Posted

技术标签:

【中文标题】Vuejs 代码在组件中不起作用,但在应用程序中起作用【英文标题】:Vuejs Code doesn't work in component yet works in app 【发布时间】:2018-11-05 04:14:21 【问题描述】:

所以我有一个非常棒的 vuejs 应用程序,它可以完美运行,但是当我将它放入 vue 组件时它失败了。我不断收到以下错误。 [Vue 警告]:编译模板时出错这是我包含的组件的代码(components.php):

    <script>Vue.component('profileinfo', 
  template: `<div id="profileInfo">
        <div class="sectionHeader">Profile</div>
        <div class="dataPoint">First:&nbsp;firstNameBraintree</div>
        <div class="dataPoint">Last:&nbsp;lastNameBraintree</div>
        <div class="dataPoint">Company:&nbsp;companyBraintree</div>
        <div class="dataPoint">Email:&nbsp;emailBraintree</div>
        <div class="dataPoint">Phone:&nbsp;phoneBraintree</div>
        <div class="buttonDiv">
            <input class="button" type="button" value="Update" v-on:click="showUpdateProfileForm()">
        </div>
      </div>
<!--Show Update Profile Form-->
<div class="updateProfileForm" v-show="showupdateprofileinfoform==true">

      <h2>Update Account Information</h2>
            <h2>Username: <?php echo $_SESSION['username'];?></h2>
      <!--PASSWORD-->
      <div class="inputDiv">
      <p v-show="passwordLengthMet==true && passwordHasCap==true && passwordHasNum==true || password.length=='' && passwordHasCap==false && passwordHasNum==false">Password * <i class="fa fa-check-circle success"></i> Valid</p>
          <p v-show="passwordLengthMet==false && password.length!='' || passwordLengthMet==true && passwordHasCap==false || passwordLengthMet==true && passwordHasNum==false">Password * <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Password must be at least 8 characters, Have a capital letter and contain a number</span></i></p>
       <input type="password" v-model="password" placeholder="********" v-on:focus="showpasswordrequirements">
         <ul v-show="dispas-s-r==true">
          <li v-show="passwordLengthMet==false || password==''">Must contain at least 8 characters</li>
             <li v-show="passwordHasCap==false">Must contain capital letter</li>
             <li v-show="passwordHasNum==false">Must contain number</li>
        </ul>
    </div>
      <!--END PASSWORD-->

      <!--PASSWORDS MATCH-->
    <div class="inputDiv">
      <p v-show="passwordsMatch==true">Confirm Password* <i class="fa fa-check-circle success"></i> Passwords Match</p>
         <p v-show="passwordsMatch==false">Confirm Password* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please make sure passwords match</span></i></p>
     <input type="password" v-model="confirmPassword" placeholder="********" v-on:focus="showconfirmpasswordrequirements">
        <ul v-show="disconfr==true">
        <li class="blue" v-show="passwordsMatch==false || confirmPassword==''">Please be sure your passwords match</li>
        </ul>
    </div>
      <!--END PASSWORDS MATCH-->

      <!--FIRSTNAME-->
    <div class="inputDiv">
      <p v-show="validFirstname==true">First name* <i class="fa fa-check-circle success"></i> Valid</p>
      <p v-show="validFirstname==false && sub==1">First Name* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please enter your firstname</span></i></p>
        <p v-show='validFirstname==false && sub!="1"'>First Name* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Please enter a firstname</span></i></p>
        <input v-model="firstName" placeholder="Firstname" v-on:focus="showfirstnamerequirements">
        <ul v-show='disfnamer==true'>
        <li v-show="validFirstname==false">Please enter a firstname</li>
        </ul>
    </div>
      <!--END FISTNAME-->

      <!--LASTNAME-->
    <div class="inputDiv">
      <p v-show="validLastname==true">Last Name* <i class="fa fa-check-circle success"></i> Valid</p>
      <p v-show="validLastname==false && sub==1">Last Name* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please enter your lastname</span></i></p>
        <p v-show='validLastname==false && sub!="1"'>Last Name* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Please enter a lastname</span></i></p>
        <input v-model="lastName" placeholder="Last name" v-on:focus="showlastnamerequirements">
        <ul v-show='dislnamer==true'>
        <li v-show="validLastname==false">Please enter a lastname</li>
        </ul>
    </div>
      <!--END LASTNAME-->

      <!--EMAIL-->
    <div class="inputDiv">
        <p v-show="validEmail==true">Email* <i class="fa fa-check-circle success"></i> Valid</p>
        <p v-show="validEmail==false && email!=='' || email=='' && sub==1">Email* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please enter a valid email</span></i></p>
        <p v-show="email=='' && sub==0">Email* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Please enter a valid email</span></i></p>
      <input v-model="email" placeholder="jchang@example.com" v-on:focus="showemailrequirements">
        <ul v-show='disemailr==true'>
        <li v-show="validEmail==false">Please enter a valid email</li>
        </ul>
      </div>
        <!--END EMAIL-->

        <!--PHONE -->
        <div class="inputDiv">
        <p v-show="phoneLength==true && phoneHasNum==true && phoneNumber!=''">Phone* <i class="fa fa-check-circle success"></i> Valid</p>
        <p v-show="phoneLength==false && phoneNumber!='' || phoneHasNum==false && phoneNumber!='' || phoneNumber=='' && sub==1">Phone* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Phone Number must have at least 10 numbers and have no letters, parenthis or dashes</span></i></p>
        <p v-show="phoneNumber=='' && sub==0">Phone* <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Phone Number must have at least 10 numbers and have no letters it cannot contain parenthis or dashes</span></i></p>
        <input v-model="phoneNumber" placeholder="Phone Number 1234567890" v-on:focus="showphonenumberrequirements" id="phoneNumber">
        <ul v-show="disphoner==true">
        <li v-show="phoneLength==false">Phone number must be 10 numbers long</li>
        <li v-show="phoneHasNum==false || phoneNumber==''"> Phone number must contain only numbers</li>
        </ul>
      </div>
        <!--END PHONE-->

        <!--COMPANY NAME-->
        <div class="inputDiv">
            <p v-show="validCompanyName==true">Company Name* <i class="fa fa-check-circle success"></i> Valid</p>
            <p v-show="validCompanyName==false && companyName!='' || companyName==false && companyName=='' && sub==1">Company Name* <i class="fa fa-exclamation-circle tooltip error"><span class="tooltiptext">Please enter your company name</span></i></p>
            <p v-show="companyName=='' && sub==0">Company Name*  <i class="fa fa-question-circle tooltip" style="color:darkblue;"><span class="tooltiptext blue" style="background-color:darkblue;">Please enter your company name</span></i></p>
            <input v-model="companyName" placeholder="Company Name" v-on:focus="showcompanynamerequirements">
            <ul v-show="discompr==true">
            <li v-show="validCompanyName==false">Please enter your company name</li>
            </ul>
      </div>
        <!--END COMPANY NAME-->

       <div class="inputDiv">
                <div class="sliderWrapper">
                    <div><strong>Subscribe to Email List</strong></div>
            <label class="switch">
                <input type="checkbox" v-model="subscribe" value="1">
                <span class="slider"></span>
            </label>
        </div>
      </div>
    <div class="inputButton">
      <input v-on:click="updateAccount()" type="button" class="saveProfileButton" value="Update">
    </div>
    <div class="inputButton">
          <input v-on:click="hideUpdateProfileForm()" type="button" class="cancelProfileButton" value="Cancel">
    </div>
  </div>
<!--End Update Profile Form-->`,
  data() 
    return 
    showSpinner: false,
    showupdateprofileinfoform: false,
    password: '',
    confirmPassword: '',
    firstName: '',
    lastName: '',
    email: '',
    sub: '',
    subscribe:'',
    dispas-s-r: '',
    disconfr: '',
    disfnamer: '',
    dislnamer: '',
    disemailr: '',
    disphoner: '',
    discompr: '',
    phoneNumber: '',
    companyName: '',
     customerId: '<?php echo $customer->id; ?>',
    companyBraintree:'<?php echo $customer->company; ?>',
    firstNameBraintree:'<?php echo $customer->firstName; ?>',
    lastNameBraintree:'<?php echo $customer->lastName; ?>',
    phoneBraintree:'<?php echo $customer->phone; ?>',
    emailBraintree:'<?php echo $customer->email; ?>',
    phone:'',
    updated: ''
    
  ,
    computed: 
    passwordsMatch: function() 
        this.confirmPassword=this.confirmPassword.replace(/\s/g, '');
      if(this.password == this.confirmPassword) 
        return true;
       else 
        return false;
      
    ,
    passwordLengthMet: function() 
        this.password=this.password.replace(/\s/g, '');
      if(this.password.trim().length >0 && this.password.trim().length >= 8) 
        return true;
       else 
        return false;
      
    ,
    passwordHasCap: function()
      if(/[A-Z]/.test(this.password))return true; elsereturn false;         
    ,
    passwordHasNum: function()
      if(/[\d]/.test(this.password))return true; elsereturn false;  
    ,
    validEmail: function() 
        this.email=this.email.replace(/\s/g, '');
      var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]2,4)$/;
      if (!reg.test(this.email)) 
        return false;
      
      return true;
    ,
      validLastname: function() 
          this.lastName=this.lastName.replace(/\s/g, '');
          if(this.lastName.trim().length<1)return false; else return true;
      ,
      validFirstname: function() 
          this.firstName=this.firstName.replace(/\s/g, '');
       if(this.firstName.trim().length<1)return false; elsereturn true;   
      ,
      validCompanyName: function()
          if(this.companyName.trim().length<1)return false; elsereturn true;
      ,
      phoneHasNum: function()
          if(isNaN(this.phoneNumber))return false; else return true;
      ,
      phoneLength: function()
          this.phoneNumber=this.phoneNumber.replace(/[^0-9]+/g, '');
          if(this.phoneNumber.trim().length==10)return true; elsereturn false;
      
  ,
    created: function() 
      this.subscribe=1;
      this.firstName='<?php if(isset($_SESSION['firstname']))echo $_SESSION['firstname'];?>';
      this.lastName='<?php if(isset($_SESSION['lastname']))echo $_SESSION['lastname'];?>';
      this.email='<?php if(isset($_SESSION['email']))echo $_SESSION['email'];?>';
      this.companyName='<?php if(isset($_SESSION['companyname']))echo $_SESSION['companyname'];?>';
      this.phoneNumber='<?php if(isset($_SESSION['phonenumber']))echo $_SESSION['phonenumber'];?>';
  ,
  methods: 
  showUpdateProfileForm: function()
      this.showupdateprofileinfoform=true;
  ,
  hideUpdateProfileForm: function()
  this.showupdateprofileinfoform=false;
,
    updateAccount: function() 
        this.sub=1;
      if(this.validFirstname && this.validLastname && this.validEmail && this.passwordsMatch && this.validCompanyName && this.phoneHasNum && this.firstName!='' && this.lastName!='' && this.email!='' && this.phoneNumber!='' && this.companyName!='' && this.passwordLengthMet && this.passwordHasNum && this.passwordHasCap && this.password!='' && this.confirmPassword!='' || this.validFirstname && this.validLastname && this.validEmail && this.passwordsMatch && this.validCompanyName && this.phoneHasNum && this.firstName!='' && this.lastName!='' && this.email!='' && this.phoneNumber!='' && this.companyName!='' && this.password=='' && this.confirmPassword=='') 
        var jsonString = JSON.stringify(
          firstName: this.firstName,
          lastName: this.lastName,
          password: this.password,
          email: this.email,
          phoneNumber: this.phoneNumber,
          companyName: this.companyName,
          subscribe: this.subscribe
        );

        $.ajax(
          url: 'updateAccountInfoBackend.php',
          dataType: 'json',
          type: 'post',
          contentType: 'application/json',
          dataType: 'json',
          data: jsonString,
            error: function(data)
              alert('error');
//                window.location.href='successfullycreated.php';
            ,
          success: function(data)
            console.log(data);
              alert('success');
              if(data.updated==1)location.reload();
              if(data.updated==0)location.reload();
          .bind(this)
        );
    
    ,
      showpasswordrequirements: function()
          this.sub=0;
          this.dispas-s-r=true;
          this.disconfr=false;
          this.disfnamer=false;
          this.dislnamer=false;
          this.disemailr=false;
          this.disphoner=false;
          this.discompr=false;
      ,
      showconfirmpasswordrequirements: function()
          this.sub=0;
          this.dispas-s-r=false;
          this.disconfr=true;
          this.disfnamer=false;
          this.dislnamer=false;
          this.disemailr=false;
          this.disphoner=false;
          this.discompr=false;
      ,
      showfirstnamerequirements: function()
          this.sub=0;
          this.dispas-s-r=false;
          this.disconfr=false;
          this.disfnamer=true;
          this.dislnamer=false;
          this.disemailr=false;
          this.disphoner=false;
          this.discompr=false;
      ,
      showlastnamerequirements: function()
          this.sub=0;
          this.dispas-s-r=false;
          this.disconfr=false;
          this.disfnamer=false;
          this.dislnamer=true;
          this.disemailr=false;
          this.disphoner=false;
          this.discompr=false;
      ,
      showemailrequirements: function()
          this.sub=0;
          this.dispas-s-r=false;
          this.disconfr=false;
          this.disfnamer=false;
          this.dislnamer=false;
          this.disemailr=true;
          this.disphoner=false;
          this.discompr=false;
      , 
      showphonenumberrequirements: function()
          this.sub=0;
          this.disphoner=true;
           this.dispas-s-r=false;
          this.disconfr=false;
          this.disfnamer=false;
          this.dislnamer=false;
          this.disemailr=false;
          this.discompr=false;
    ,
      showcompanynamerequirements: function()
          this.sub=0;
          this.disphoner=false;
           this.dispas-s-r=false;
          this.disconfr=false;
          this.disfnamer=false;
          this.dislnamer=false;
          this.disemailr=false;
          this.discompr=true;
      
  
);

这是 vue 应用程序本身的代码:

<?php session_start(); ob_start(); unset($_SESSION['accountupdated']); unset($_SESSION['inserteddisplay']); unset($_SESSION['updateddisplay']); unset($_SESSION['creditcardupdated']);
if(isset($_SESSION['didnotdelete']) && $_SESSION['didnotdelete']==1)header('location:unabletodelete.php');
if(isset($_SESSION['accessdenied']) && $_SESSION['accessdenied']==1)header('location:logout.php');
if(isset($_SESSION['accountupdated']) && $_SESSION['accountupdated']==0)header('Location:updateaccountinfoerror.php');
if(isset($_SESSION['kill']) && $_SESSION['kill']==1)header('Location:updateaccountinfoerror.php');
if(isset($_SESSION['creditcardnotupdated']) && $_SESSION['creditcardnotupdated']==1)header('Location:errorupdatingcreditcard.php');
if(isset($_SESSION['didnotinsertdisplay']) && $_SESSION['didnotinsertdisplay']==1)header('Location:errorinsertingdisplay.php');
if(isset($_SESSION['displaynotauthorized']) and $_SESSION['displaynotauthorized']=1)header('Location:notautorizedtoupdatedisplay.php');
if(isset($_SESSION['didnotupdatedisplay']) && $_SESSION['didnotupdatedisplay']==1)header('Location:didnotupdatedisplay.php');
$validyear=$_SESSION['validyear'];
$currentmonthyear=$_SESSION['currentmonthyear'];
  date_default_timezone_set('America/Denver');
  $id = htmlspecialchars($_GET["id"]);
//if(isset($_GET['id']) and $_GET['id']!=$_SESSION['braintreeid'])header('Location:logout.php');
if(!isset($_SESSION['username']))header('Location:logout.php');
  require_once 'lib/Braintree.php';
  require_once('head.php');
  require_once('header.php');

  $gateway = new Braintree_Gateway([
    'environment' => 'sandbox',
    'merchantId' => 'key',
    'publicKey' => 'key',
    'privateKey' => 'key'
  ]);

  $customer = $gateway->customer()->find($id);
  $plans = $gateway->plan()->all();

  $plansArray = array();

  foreach ($plans as $plan) 
    array_push($plansArray, $plan);
  

  $subscriptions = array();

  foreach ($customer->creditCards as $card) 
    foreach ($card->subscriptions as $subscription) 
      array_push($subscriptions, $subscription);
    
  
?>
    <!doctype html>
    <html>
    <head>
      <title>Get Customers</title>
      <link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
      <script src="vue.js"></script>
      <script src="jquery-3.3.1.js"></script>
     <?php require_once('components.php');?>
    </head>
    <body>
      <div id="app">
      <div class="profile-containter">
     <profileinfo></profileinfo>
          </div>
    </div>
    <!--End Update Display Form -->
    <script>
        var app = new Vue(
          el: '#app',
          data: 

          ,
          methods: 

          
        );

      </script>
    <?php include('foot.php');?>
    </body>
    </html>

再次奇怪的是,如果我把它放在一个 vue 应用程序中,它可以完美地工作,但是当我把它放在一个 Vuejs 组件中时,它突然就不能工作了。我觉得这非常非常奇怪,因为它本质上是相同的代码。如果你们中的任何一个天才编码员有任何建议,我将不胜感激。非常感谢。

【问题讨论】:

看起来你的模板没有单个根元素,我用另一个 div 包裹它,它可以工作。 这行得通,但为什么呢?我将它包装在一个带有类配置文件容器的 div 中,为什么这不起作用。 【参考方案1】:

正如@Max Sinev 提到的,您的模板没有单个 根元素,这是不可能的(请参阅official documentation)。

为了解决这个问题,您只需将所有 html 代码包装在一个 div 中,如下所示:

<div>
    <div id="profileInfo">
    ...
        <div class="inputButton">
          <input v-on:click="hideUpdateProfileForm()" type="button" class="cancelProfileButton" value="Cancel">
    </div>
  </div>
</div>

【讨论】:

以上是关于Vuejs 代码在组件中不起作用,但在应用程序中起作用的主要内容,如果未能解决你的问题,请参考以下文章

脚本在实际服务器中不起作用,但在 localhost XAMPP 中起作用

模态在我的网络服务器中不起作用,但在 localhost 中起作用。这是为啥?

SQL 查询在 Excel 中不起作用,但在 Access 中起作用

某些功能在“发布”部署中不起作用(但在“调试”中起作用)

推送通知在 TestFlight 中不起作用,但在 Xcode 中起作用

Boost union 在 1.67 中不起作用,但在 1.61 中起作用。为啥?