Vue 2.0 Laravel 5.3 Parent Child relationship with slot - laravel-5.3

I have a project where when i click on a anchor on parent item-sorting-list a property of child item-card will change so it sort something out based on that property. However the data does not seem to pass to the child. I am wondering if there is anything wrong when i built up the parent child relationship in the meanwhile?
template (item-sorting-list)
<a :name="subcat.name" href="" #click.prevent="getSelectedSubcat(subcat.name)">{{subcat.name}}</a>
methods (item-sorting-list)
methods: {
getSelectedSubcat(subcat){
var vm = this;
vm.selectedSubcat = subcat
}
}
When I click on the subcat.name, it does actually store subcat.name into selectedSubcat (verified from Vue devtool) in the item-sorting-list component. The problem is item-card does not store it even though i put selectedSubcat as props
HTML (does this work as parent child relationship here?)
<item-sorting-list><item-card></item-card></item-sorting-list>
UPDATED item-card
export default {
props:[
'selectedSubcat'
],
data(){
return {
products:[],
}
},
mounted() {
this.getAllProducts()
},
methods: {
getAllProducts(){
var vm = this;
vm.$http.get('/getProducts').then((response)=>{
vm.products = response.data.data.products;
});
}
}
}
from Vue devtool, item-card is included in the item-sorting-list, I would say that means they are parent child relationship? but then when i click something in item-sorting-list and change selectedSubcat, selectedSubcat in item-sorting-list does change but the selectedSubcat in item-card remains undefined. Sorry for my bad English.
UPDATE2
I notice that every example that I found online is that they set selectedSubcat in the new Vue with el="#app" in it instead of any other component (in my case item-sorting-list). Does that matter? I feel like the :selected-subcat="selectedSubcat in
<item-sorting-list>
<item-card :selected-subcat="selectedSubcat"></item-card>
</item-sorting-list>
cannot read the selectedSubcat that I defined in the component item-sorting-list but instead if i set selectedSubcat in the following
const app = new Vue({
el: '#app',
data:{
selectedSubcat:1
}
});
it does read selectedSubcat as 1. So what I would say is that item-card does not consider item-sorting-list as its parent. But why and how can I make it to become item-card's parent? [NOTE: but in the Vue devtool the tree does show that item-sorting-list does consist of item-card, item-card does show after clicking the arrow on the left of item-sorting-list]

In VueJs, you have parent child relation, when you don't register a vue component globally, but you make a component available only in the scope of another instance/component by registering it with the components instance option, like following:
var Child = {
template: '<div>A custom component!</div>'
}
new Vue({
// ...
components: {
// <my-component> will only be available in parent's template
'my-component': Child
}
})
In your case, I dont see selectedSubcat being passed as dynamic props to child component item-card. Dynamic props to data on the parent ensures whenever the data is updated in the parent, it will also flow down to the child:
You probably have to pass it to child like following:
<item-sorting-list>
<item-card :selected-subcat="selectedSubcat"></item-card>
</item-sorting-list>
You also have to add props in your item-list like this:
var itemList = {
props: ["selectedSubcat"]
template: '<div>Yout component!</div>'
}
notice I have converted it to kebab-case, because HTML being case-insensitive, camelCased prop names need to use their kebab-case (hyphen-delimited) equivalents(Documentation).

Related

How do I override CSS custom properties in React?

I want to dynamically set the max-height of an element based on the number of children it has.
In my component, I am setting a custom property using:
document.documentElement.style.setProperty('--children-count', Children.count(props.children));
and in my css, I use it like this:
&.active {
.buttonGroup {
max-height: calc(var(--children-count) * 30px);
}
}
This works fine if I am only using it once. However, once I start loading multiple instances of the component with different number children, the --children-count gets overwritten and all the preceding components styles get changed.
How do I go around this?
The issue is most probably because you change the value of the --children-count CSS variable on the top documentElement, therefore affecting ALL your components in the document.
If you want 1 value per Component then simply apply it on an Element of said Component, see e.g. How to apply CSS variable on dynamic CSS class in dynamic component
If you use styled-components, you can also use style adaptation based on props (instead of CSS variables).
If you need to sync common data between multiple components, pull state upwards! In this case, into a context (unless if you want to manage it with props).
Here's a codesanbox: https://codesandbox.io/s/nervous-lalande-wjpdgb
The key parts of it are the Context Provider which will handle the shared state
function ChildCounterContextProvider({ children }) {
const [count, setCount] = useState(0);
const value = useMemo(() => ({ count, setCount }), [count])
useEffect(() => {
// Handle changes to number of children here
document.documentElement.style.setProperty('--children-count', count);
}, [count]);
return <ChildCounterContext.Provider value={value}>
{children}
</ChildCounterContext.Provider>
}
...and the context consumer, which will write to it.
const useChildCounter = () => useContext(ChildCounterContext);
function MyComponentWithChildren({ children }) {
const childrenCount = React.Children.count(children);
const childCounter = useChildCounter();
useEffect(() => {
// Add when enters
childCounter.setCount(n => n+childrenCount);
// Deduct when exits
return () => childCounter.setCount(n => n-childrenCount);
}, [childrenCount, childCounter]);
return <p>I have {childrenCount} children out of {childCounter.count}</p>
}
The effects will make sure the counts is always in sync.

Change css variables dynamically in angular

In my angular project, I have some css variables defined in top level styles.scss file like this. I use these variable at many places to keep the whole theme consistent.
:root {
--theme-color-1: #f7f7f7;
--theme-color-2: #ec4d3b;
--theme-color-3: #ffc107;
--theme-color-4: #686250;
--font-weight: 300
}
How can I update values of these variables dynamically from app.component.ts ? And What is the clean way to do this in angular ?
You can update them using
document.documentElement.style.setProperty('--theme-color-1', '#fff');
If u want to update many values, then create a object
this.styles = [
{ name: 'primary-dark-5', value: "#111" },
{ name: 'primary-dark-7_5', value: "#fff" },
];
this.styles.forEach(data => {
document.documentElement.style.setProperty(`--${data.name}`, data.value);
});
The main thing here is document.documentElement.style.setProperty. This line allows you to access the root element (HTML tag) and assigns/overrides the style values.
Note that the names of the variables should match at both places(css and js files)
if you don't want to use document API, then you can use inline styles on HTML tag directly
const styleObject = {};
this.styles.forEach(data => {
styleObject[`--${data.name}`] = data.value;
});
Then In your template file using ngStyle (https://angular.io/api/common/NgStyle)
Set a collection of style values using an expression that returns
key-value pairs.
<some-element [ngStyle]="objExp">...</some-element>
<html [ngStyle]="styleObject" >...</html> //not sure about quotes syntax
Above methods do the same thing, "Update root element values" but in a different way.
When you used :root, the styles automatically got attached to HTML tag
Starting with Angular v9 you can use the style binding to change a value of a custom property
<app-component-name [style.--theme-color-1="'#CCC'"></app-component-name>
Some examples add variables directly to html tag and it seem in the element source as a long list. I hope this helps to you,
class AppComponent {
private variables=['--my-var: 123;', '--my-second-var: 345;'];
private addAsLink(): void {
const cssVariables = `:root{ ${this.variables.join('')}};
const blob = new Blob([cssVariables]);
const url = URL.createObjectURL(blob);
const cssElement = document.createElement('link');
cssElement.setAttribute('rel', 'stylesheet');
cssElement.setAttribute('type', 'text/css');
cssElement.setAttribute('href', url);
document.head.appendChild(cssElement);
}
}

Css Selector in Framework7 vue

i try to build an Cordova/Phonegap application using vue.js and the Framework7.
I find out how to use functions like "onClick" using the "v-on:click="OnClick" attribute in an html element. Framework7 has jquery already implemented in the dom.
But there is one question. How can i access the dom directly, so that i can select whole css classes with the jquery selector. Like:
$('.likeButton'). ?
In the offical framework7 i found something like this to access the dom with its functions:
this.$$ or this.Dom7
This is what i have already written down in the home.vue file:
<script>
//import Fonts-awesome Icons
import FontAwesomeIcon from '#fortawesome/vue-fontawesome'
import {} from '#fortawesome/fontawesome-free-solid'
import F7Icon from "framework7-vue/src/components/icon";
import F7PageContent from "framework7-vue/src/components/page-content";
import * as Framework7 from "framework7";
export default {
name: 'FAExample',
components: {
F7PageContent,
F7Icon,
FontAwesomeIcon
},
methods: {
clickit: function () {
console.log("hi");
//this is what i have tested, looking if i have access to dom
let $$ = this.$$;
console.log($$);
},
//this is what i want to use
$('.likebutton').on('click',function () {
})
}
}
</script>
Did any of you have an idea how this works?
I hope you can help me. I'm new with vue.js in combination with the framework7.
Thank's for your help :)
We can use all the DOM functions just like
this.$$('.classname)
for example, if you want to hide something by jquery you can use as:
this.$$('.classname).hide()
To check all the DOM functions you can check the official documentation.
https://framework7.io/docs/dom7.html
But make sure that your DOM function should not in any Window function.
If you get the error to implemented it, just make the 'this' instance first.
Just like:
var self=this; // a global variable with this instance
use
self.$$('.classname).hide()
for any framework7 help, just ping me on skyp: sagardhiman5_1
Have you tried using Vue's $refs? You can set a reference to a specific DOM element and then access that in Vue.
A simple example:
<template>
<div class="some-item" ref="itemRef">Some item</div>
</template>
Then in the component:
var myItem = this.$refs.myItem;
// do what you want with that DOM item...
You can also access $refs from the parent. The example in the link below gives details on that.
More on $refs: https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs

AngularJS Material Dialog using component as template

I have an angular component which I want to use in an AngularJS Material dialog:
return $mdDialog.show({
template: '<publish-dialog user="$ctrl.user" target-collection="$ctrl.targetCollection"></publish-dialog>',
controller: function () {
this.user = user;
this.targetCollection = targetCollection;
},
controllerAs: '$ctrl',
targetEvent: event,
clickOutsideToClose: true
});
The problem is, that when defining the template like this, the generated html looks like this:
<md-dialog>
<publish-dialog>
<md-toolbar></md-toolbar>
<md-dialog-content></md-dialog-content>
<md-dialog-actions></md-dialog-actions>
</publish-dialog>
<md-dialog>
The component element is breaking the between md-dialog and md-toolbar, md-dialog-content and md-dialog-actions leads to a layout break and the md-toolbar and the md-dialog-actions are not fixed.
So my question is, is there a way to only render the component template contents without the component element (<publish-dialog></publish-dialog>)?
In your directive, try using replace: true.
From How to use `replace` of directive definition?

What is the best way to declare global variables in Vue.js?

I need access to my hostname variable in every component.
Is it a good idea to put it inside data?
Am I right in understanding that if I do so, I will able to call it everywhere with this.hostname?
As you need access to your hostname variable in every component, and to change it to localhost while in development mode, or to production hostname when in production mode, you can define this variable in the prototype.
Like this:
Vue.prototype.$hostname = 'http://localhost:3000'
And $hostname will be available in all Vue instances:
new Vue({
beforeCreate: function () {
console.log(this.$hostname)
}
})
In my case, to automatically change from development to production, I've defined the $hostname prototype according to a Vue production tip variable in the file where I instantiated the Vue.
Like this:
Vue.config.productionTip = false
Vue.prototype.$hostname = (Vue.config.productionTip) ? 'https://hostname' : 'http://localhost:3000'
An example can be found in the docs:
Documentation on Adding Instance Properties
More about production tip config can be found here:
Vue documentation for production tip
a vue3 replacement of this answer:
// Vue3
const app = Vue.createApp({})
app.config.globalProperties.$hostname = 'http://localhost:3000'
app.component('a-child-component', {
mounted() {
console.log(this.$hostname) // 'http://localhost:3000'
}
})
Warning: The following answer is using Vue 1.x. The twoWay data mutation is removed from Vue 2.x (fortunately!).
In case of "global" variables—that are attached to the global object, which is the window object in web browsers—the most reliable way to declare the variable is to set it on the global object explicitly:
window.hostname = 'foo';
However form Vue's hierarchy perspective (the root view Model and nested components) the data can be passed downwards (and can be mutated upwards if twoWay binding is specified).
For instance if the root viewModel has a hostname data, the value can be bound to a nested component with v-bind directive as v-bind:hostname="hostname" or in short :hostname="hostname".
And within the component the bound value can be accessed through component's props property.
Eventually the data will be proxied to this.hostname and can be used inside the current Vue instance if needed.
var theGrandChild = Vue.extend({
template: '<h3>The nested component has also a "{{foo}}" and a "{{bar}}"</h3>',
props: ['foo', 'bar']
});
var theChild = Vue.extend({
template: '<h2>My awesome component has a "{{foo}}"</h2> \
<the-grandchild :foo="foo" :bar="bar"></the-grandchild>',
props: ['foo'],
data: function() {
return {
bar: 'bar'
};
},
components: {
'the-grandchild': theGrandChild
}
});
// the root view model
new Vue({
el: 'body',
data: {
foo: 'foo'
},
components: {
'the-child': theChild
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<h1>The root view model has a "{{foo}}"</h1>
<the-child :foo="foo"></the-child>
In cases that we need to mutate the parent's data upwards, we can add a .sync modifier to our binding declaration like :foo.sync="foo" and specify that the given 'props' is supposed to be a twoWay bound data.
Hence by mutating the data in a component, the parent's data would be changed respectively.
For instance:
var theGrandChild = Vue.extend({
template: '<h3>The nested component has also a "{{foo}}" and a "{{bar}}"</h3> \
<input v-model="foo" type="text">',
props: {
'foo': {
twoWay: true
},
'bar': {}
}
});
var theChild = Vue.extend({
template: '<h2>My awesome component has a "{{foo}}"</h2> \
<the-grandchild :foo.sync="foo" :bar="bar"></the-grandchild>',
props: {
'foo': {
twoWay: true
}
},
data: function() {
return { bar: 'bar' };
},
components: {
'the-grandchild': theGrandChild
}
});
// the root view model
new Vue({
el: 'body',
data: {
foo: 'foo'
},
components: {
'the-child': theChild
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<h1>The root view model has a "{{foo}}"</h1>
<the-child :foo.sync="foo"></the-child>
I strongly recommend taking a look at Vuex, it is made for globally accessible data in Vue.
If you only need a few base variables that will never be modified, I would use ES6 imports:
// config.js
export default {
hostname: 'myhostname'
}
// .vue file
import config from 'config.js'
console.log(config.hostname)
You could also import a json file in the same way, which can be edited by people without code knowledge or imported into SASS.
For any Single File Component users, here is how I set up global variable(s)
Assuming you are using Vue-Cli's webpack template
Declare your variable(s) in somewhere variable.js
const shallWeUseVuex = false;
Export it in variable.js
module.exports = { shallWeUseVuex : shallWeUseVuex };
Require and assign it in your vue file
export default {
data() {
return {
shallWeUseVuex: require('../../variable.js')
};
}
}
Ref: https://v2.vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch
In vue cli-3 You can define the variable in main.js like
window.basurl="http://localhost:8000/";
And you can also access this variable in any component by using
the the
window.basurl
A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.
An example of this solution can be found at this answer:
https://stackoverflow.com/a/62485644/1178478

Resources